PHP - Efficiency while searching for palindrome - php

I was challenged by a friend to code some PHP to find the longest palindrome in provided text, my solution is below, how could I make it more efficient?
$string = file_get_contents("http://challenge.greplin.com/static/gettysburg.txt");
echo $string;
function isPalendrone($string) {
if ($string == strrev($string))
return true;
else
return false;
}
$longest = "";
for($i = 0; $i < strlen($string)-1; $i++) {
$afterCurrent = substr($string, $i);
for($j = 0; $j < strlen($afterCurrent)-1; $j++) {
$section = substr($afterCurrent, 0, $j);
if(isPalendrone($section)) {
if(strlen($longest)<strlen($section)) {
$longest = $section;
}
}
}
}
echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";

This reverses the entire string and just does substr() matches against each:
$rev = strrev($txt);
$len = strlen($txt);
$longest_len = 0;
$longest_str = null;
for ($i = 0; $i < $len; ++$i)
{
for ($j = $len - $i; $j > $longest_len; --$j)
{
if (substr($txt, $i, $j) == substr($rev, $len-$i-$j, $j))
{
$longest_len = $j;
$longest_str = substr($txt, $i, $j);
break;
}
}
}
I didn't try to optimize the implementation. e.g., It might be a little faster to skip the substr and do a char-by-char approach, because you could break out faster. In that case, you wouldn't really even need to reverse the string.

To get the longest palindrome - you have to start with longest string (not with shortest like you do now), check it and break on first match.
Also you'd better just keep 2 pointers ($i and $j) and not perform substr twice. It is enough to have i and j and substr once, right before you perform if(isPalendrone()) condition.
My implementation (~20% faster than yours):
<?php
$string = 'FourscoreandsevenyearsagoourfaathersbroughtforthonthiscontainentanewnationconceivedinzLibertyanddedicatedtothepropositionthatallmenarecreatedequalNowweareengagedinagreahtcivilwartestingwhetherthatnaptionoranynartionsoconceivedandsodedicatedcanlongendureWeareqmetonagreatbattlefiemldoftzhatwarWehavecometodedicpateaportionofthatfieldasafinalrestingplaceforthosewhoheregavetheirlivesthatthatnationmightliveItisaltogetherfangandproperthatweshoulddothisButinalargersensewecannotdedicatewecannotconsecratewecannothallowthisgroundThebravelmenlivinganddeadwhostruggledherehaveconsecrateditfaraboveourpoorponwertoaddordetractTgheworldadswfilllittlenotlenorlongrememberwhatwesayherebutitcanneverforgetwhattheydidhereItisforusthelivingrathertobededicatedheretotheulnfinishedworkwhichtheywhofoughtherehavethusfarsonoblyadvancedItisratherforustobeherededicatedtothegreattdafskremainingbeforeusthatfromthesehonoreddeadwetakeincreaseddevotiontothatcauseforwhichtheygavethelastpfullmeasureofdevotionthatweherehighlyresolvethatthesedeadshallnothavediedinvainthatthisnationunsderGodshallhaveanewbirthoffreedomandthatgovernmentofthepeoplebythepeopleforthepeopleshallnotperishfromtheearth';
function isPalendrone($string) {
return $string == strrev($string);
}
$longest = '';
$length = strlen($string);
for ($i = 0; $i < $length - 1; $i++) {
for ($j = $length - $i; $j > 1; $j--) {
if (isPalendrone(substr($string, $i, $j))) {
$new = substr($string, $i, $j);
if (strlen($new) > strlen($longest)) $longest = $new;
break;
}
}
}
echo "<br /><br/>The longest was: ".$longest."<br /> which is ".strlen($longest)." chars long";

Related

How to create a user defined function in PHP exactly the same as str_replace(), without using any other built-in functions except for strlen()

<?php
echo my_string_replace("world","jonathan","hello world helloworld");
function my_string_replace($find, $replace, $string)
{
//Block of codes here...
}
?>
I can only use loops, if else statements, and other commands such as break and continue. I want to create my own algorithm. Please help me. This should output : hello jonathan hellojonathan"
error_reporting(0); used for hide "Uninitialized string offset" notice.
<?php
function str_v2($num){
error_reporting(0);
for($i=0; $num[$i] != "";$i++);
echo $i; }//end of function
$name = "Hope this will work.";
echo str_v2($name);
?>
That was a fun brain teaser. Here you go:
echo my_string_replace("world", "jonathan", "hello world helloworld");
function my_string_replace($find, $replace, $string)
{
$characterCount = strlen($string);
$findCount = strlen($find);
$replaceCount = strlen($replace);
for ($i = 0; $i < $characterCount - $findCount +1; $i++) {
if ($string[$i] == $find[0]) {
$j = 1;
$found = true;
while ($j < $findCount) {
if ($string[$i + $j] != $find[$j]) {
$found = false;
break;
}
$j++;
}
if ($found) {
// copy string until current position
$replaced = '';
for ($x = 0; $x < $i; $x++) {
$replaced .= $string[$x];
}
// append replacement
$replaced .= $replace;
// copy after match till end
for ($x = $i + $findCount; $x < $characterCount; $x++) {
$replaced .= $string[$x];
}
// continue with replaced string, after replacement
$string = $replaced;
$characterCount = strlen($string);
$i = $i + $replaceCount;
}
}
}
return $string;
}

How to replace multiple random characters in string with underscore(_) in PHP

I am using codes like "gjhyYhK", "HJjhkeuJ" etc. But want user to show these codes like:
gj_y__K
HJj__e_J
means code will be edited with "_" at random positions in code.
This will do what you want:
$str = "gjhyYhK";
$len = strlen($str);
$num_to_remove = ceil($len * .4); // 40% removal
for($i = 0; $i < $num_to_remove; $i++)
{
$k = 0;
do
{
$k = rand(1, $len);
} while($str[$k-1] == "_");
$str[$k-1] = "_";
}
print $str . "\n";
If you want more underscores, change the value of $underscores. This will guarantee you get how many underscores you want, so long as you want fewer than the length of the string
Try this:
$string=array(
'gjhyYhK',
'HJjhkeuJ'
);
$arr=array();
foreach ($string as $key=>$value) {
$arr[$key]='';
for ($i=1; $i <=strlen($value); $i++) {
if(rand(0,1)){
$arr[$key].=substr($string[$key],$i,1);
}else{
$arr[$key].='_';
}
}
}
var_dump($arr);
you can try below code to get the functionality what you are looking for
<?php
$string = "gjhyYhK";
$percentage = 40;
$total_length = strlen($string);
$number_of_underscore = floor(($percentage / 100) * $total_length); // I have use floor value, you can use ceil() as well
for ($i = 1; $i <= $number_of_underscore; $i++)
{
$random_position = rand(0, strlen($string) - 1); // get the random position of character to be replaced
if (substr($string, $random_position, 1) !== '_') // check if its already replaced underscore (_)
{
$string = preg_replace("/" . (substr($string, $random_position, 1)) . "/", '_', $string, 1); // here preg_replaced use to replace the character only once, (i.e str_replace() will replace all matching characters)
}
else
{
$i--; // else decrement $i for the loop to run one more time
}
}
echo $string;
?>
let me know if any other help needed
$str = "ADFJ";
$strlen = strlen($str);
$newStr = '';
for ($i = 0; $i < $strlen; $i++) {
if ($i == rand(0, $strlen)) {
$newStr .= '_';
} else {
$newStr .= $str[$i];
}
}
echo $newStr;

Replacing char with number

There is this code that I am doing
Example a string of this value
z12z
I want to generate it
0120
0121
0122
... until 0129
then
1120
1121
1122
... until 1129
until 9129 , its sort of like two four loop, but I got no idea how to implement this.
and the issue is z can be anywhere and it can be zzzz
where it will be
0000 until 9999
or it could also be z0z0, z could be anywhere. What kind of method should I use for such.
Thanks!
I am doing it with php
for every occurance of letter 'z' , i will need do a for loop to generate the possible number, from 0 to 9, you can say z is a for loop for 0 to 9, e.g z555 will yield 0555,1555,2555,3555,4555,5555,6555,7555,8555,9555 , issue is z can occur with a possibility of 0 to 4, like z555 , zz55,zzz5, zzzz, and z position is random , I need generate the possible z number output
z position could be 55z5 , 5z55 , 5zz5 . its does not have a fix position.
<?php
$numbers = array();
for ($i = 0; $i <= 9; $i++){
for ($j = 120; $j <= 129; $j++){
$numbers[] = $i . $j;
}
}
print_r('<pre>');
print_r($numbers);
A better answer that take the z char is:
<?php
function strReplaceNth($search, $replace, $subject, $nth)
{
$found = preg_match_all('/' . preg_quote($search) . '/', $subject, $matches, PREG_OFFSET_CAPTURE);
if (false !== $found && $found > $nth) {
return substr_replace($subject, $replace, $matches[0][$nth][1], strlen($search));
}
return $subject;
}
function cleanup($numbers, $char)
{
$tmp = array();
for ($i = 0; $i < count($numbers); $i++){
if (strpos($numbers[$i], $char) === false){
$tmp[] = $numbers[$i];
}
}
return $tmp;
}
function generateNumber($numbers, $char)
{
if (!is_array($numbers)){
if (strpos($numbers, $char) === false){
return array($numbers);
} else {
$tmp = $numbers;
$numbers = array();
for ($j = 0; $j <= 9; $j++){
$numbers[] = strReplaceNth($char, $j, $tmp, 0);
}
return generateNumber($numbers, $char);
}
} else {
for ($i = 0; $i < count($numbers); $i++){
if (strpos($numbers[$i], $char) === false){
return cleanup($numbers, $char);
} else {
$numbers = array_merge($numbers, generateNumber($numbers[$i], $char));
}
}
return generateNumber($numbers, $char);
}
}
function getCharPos($string, $char)
{
$pos = array();
for ($i = 0; $i < strlen($string); $i++){
if (substr($string, $i, 1) == $char){
$pos[] = $i;
}
}
return $pos;
}
$string = 'z12z';
$char = 'z';
$occurences = getCharPos($string, $char);
$numbers = array();
if (count($occurences) > 0){
$numbers = generateNumber($string, $char);
} else {
$numbers[] = $string;
}
print_r('<pre>');
print_r($numbers);die();

Optimal function to create a random UTF-8 string in PHP? (letter characters only)

I wrote this function that creates a random string of UTF-8 characters. It works well, but the regular expression [^\p{L}] is not filtering all non-letter characters it seems. I can't think of a better way to generate the full range of unicode without non-letter characters.. short of manually searching for and defining the decimal letter ranges between 65 and 65533.
function rand_str($max_length, $min_length = 1, $utf8 = true) {
static $utf8_chars = array();
if ($utf8 && !$utf8_chars) {
for ($i = 1; $i <= 65533; $i++) {
$utf8_chars[] = mb_convert_encoding("&#$i;", 'UTF-8', 'HTML-ENTITIES');
}
$utf8_chars = preg_replace('/[^\p{L}]/u', '', $utf8_chars);
foreach ($utf8_chars as $i => $char) {
if (trim($utf8_chars[$i])) {
$chars[] = $char;
}
}
$utf8_chars = $chars;
}
$chars = $utf8 ? $utf8_chars : str_split('abcdefghijklmnopqrstuvwxyz');
$num_chars = count($chars);
$string = '';
$length = mt_rand($min_length, $max_length);
for ($i = 0; $i < $length; $i++) {
$string .= $chars[mt_rand(1, $num_chars) - 1];
}
return $string;
}
\p{L} might be catching too much. Try to limit to {Ll} and {LU} -- {L} includes {Lo} -- others.
With PHP7 and IntlChar there is now a better way:
function utf8_random_string(int $length) : string {
$r = "";
for ($i = 0; $i < $length; $i++) {
$codePoint = mt_rand(0x80, 0xffff);
$char = \IntlChar::chr($codePoint);
if ($char !== null && \IntlChar::isprint($char)) {
$r .= $char;
} else {
$i--;
}
}
return $r;
}

PHP Random Number

I want to generate a random number in PHP where the digits itself should not repeat in that number.
Is that possible?
Can you paste sample code here?
Ex: 674930, 145289. [i.e Same digit shouldn't come]
Thanks
Here is a good way of doing it:
$amountOfDigits = 6;
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $amountOfDigits;$i++)
$digits .= $numbers[$i];
echo $digits; //prints 217356
If you wanted it in a neat function you could create something like this:
function randomDigits($length){
$numbers = range(0,9);
shuffle($numbers);
for($i = 0;$i < $length;$i++)
$digits .= $numbers[$i];
return $digits;
}
function randomize($len = false)
{
$ints = array();
$len = $len ? $len : rand(2,9);
if($len > 9)
{
trigger_error('Maximum length should not exceed 9');
return 0;
}
while(true)
{
$current = rand(0,9);
if(!in_array($current,$ints))
{
$ints[] = $current;
}
if(count($ints) == $len)
{
return implode($ints);
}
}
}
echo randomize(); //Numbers that are all unique with a random length.
echo randomize(7); //Numbers that are all unique with a length of 7
Something along those lines should do it
<?php
function genRandomString() {
$length = 10; // set length of string
$characters = '0123456789'; // for undefined string
$string ="";
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string;
}
$s = genRandomString(); //this is your random print var
or
function rand_string( $length )
{
$chars = "0123456789";
$size = strlen( $chars );
for( $i = 0; $i < $length; $i++ )
{
$str .= $chars[ rand( 0, $size – 1 ) ];
}
return $str;
}
$rid= rand_string( 6 ); // 6 means length of generate string
?>
$result= "";
$numbers= "0123456789";
$length = 8;
$i = 0;
while ($i < $length)
{
$char = substr($numbers, mt_rand(0, strlen($numbers)-1), 1);
//prevents duplicates
if (!strstr($result, $char))
{
$result .= $char;
$i++;
}
}
This should do the trick. In $numbers you can put any char you want, for example: I have used this to generate random passwords, productcodes etc.
The least amount of code I saw for something like this was:
function random_num($n=5)
{
return rand(0, pow(10, $n));
}
But I'm assuming it requires more processing to do this than these other methods.

Categories