Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP compare two string in random position

Tags:

php

PHP to compare two string

Example I got a string of number

1 2 2 1  and another is 2 1 2 1

The result would be true since its just a shuffle of position for 1 2 2 1 and 2 2 1 1

But if the value is

1 2 2 2 and another is 2 1 2 1

the result would return false because in the first string it got 3 occurrence of 2, no matter how we shuffle 1 2 2 2 position it would not give a 2 1 2 1

another possible example would be

1 2 3 1 and another is 1 2 3 3

the result would be false also because no matter how we shuffle 1231 would not give us 1233

how can i do this comparison, is there any php function that can compare a shuffle string against a non shuffle one

Maybe I could use str_shuffle and do a array push for unique until I get 24 combination of this string.

$input_string = "1221";
$array_string = ();

while( count($array_string) != 24 )
{
    $input_string = str_shuffle($input_string);
    array_push($array_string, $input_string);
    $array_string = array_unique($array_string);
}

//then lastly i check if compare string is in array

is this the right way to do this ?

Edit: another suggestion which seems to do better is split the string into array and sort it . which I think will save more computing power !

like image 618
Baoky chen Avatar asked Jun 13 '26 06:06

Baoky chen


1 Answers

$string1 = "1122";
$string1 = str_split($string1);
sort($string1);

$string2 = "1212";
$string2 = str_split($string2);
sort($string2);

if ($string1 == $string2) {
    echo "true";
} else {
    echo "false";
}

Here is an example that returns true

like image 65
Zack Avatar answered Jun 15 '26 03:06

Zack



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!