3

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 !

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
Baoky chen
  • 99
  • 2
  • 10

7 Answers7

6
$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

Zack
  • 874
  • 1
  • 9
  • 18
  • This is what I would use, since this does not rely on the content of the strings (it can be numbers OR letters) or its delimiters (Robin's answer asumes the delimiters would always be spaces). – Petr Cibulka Aug 31 '14 at 07:01
1

You can compare the contents of 2 lists regardless of order very efficiently, by first sorting both lists then comparing them. If both of the sorted versions are identical, then it is possible to shuffle one string into the other.

This is actually called an anagram (and it can be done with letters too).

If the numbers are all single digit then you can sort the characters in the string. If the letters are multiple digits, then you must first construct an array of integers and sort them.

How Long It Will Take

This method will take time proportional to length * log(length) (where length is the length of the strings), because that's how long the sorting takes. That is the algorithm has time complexity O(n lg(n)).

Community
  • 1
  • 1
BudgieInWA
  • 2,184
  • 1
  • 17
  • 31
1

What you want is to check whether a numeric string is an anagram of another. You can map each number to a prime number, take a product of the mapped numbers and then perform an equality. Same idea can be used to make it work for alphanumeric strings. This wouldn't work for long strings as that will result in an integer overflow. If you anticipate long strings, a counting approach is better. Unlike splitting, sorting and comparing two arrays, this runs in O(n).

$primeMap = array(2, 3, 5, 7, 11, 13, 17, 19, 23, 29);

function isNumericAnagram ($n1, $n2) {
  if(strlen($n1) !== strlen($n2)) return false;
  $p1 = $p2 = 1;
  for($i = 0; $i < strlen($n1); $i ++) {
    $p1 *= $primeMap[$n1[$i]];
    $p2 *= $primeMap[$n2[$i]];
  }
  return $p1 === $p2;

}


isNumericAnagram ('1234', '3214'); //true
isNumericAnagram ('12534', '35214'); //true
isNumericAnagram ('0000', '0000'); //true
isNumericAnagram ('11', '1'); //false

From the Fundamental Theorem Of Arithmetic,

any integer greater than 1 can be written as a unique product (up to ordering of the factors) of prime numbers

c.P.u1
  • 16,664
  • 6
  • 46
  • 41
1

The assumptions I'm making here are that your strings only contain number and space characters and the numbers are separated by spaces (i.e. they are all integer values). Given these assumptions, and assuming you are seeking the most performant way to solve this problem my solution would be the following.

/**
*
*  A function that returns TRUE or FALSE if both strings
*  are an anagram. Assumed space-delimited integer strings.
*
*/
function identStrings($string1, $string2) {

    $token = strtok($string1, " "); // tokenize the string by spaces
    $numbers = array_map('intval',array_filter(explode(' ', $string2)));

    while($token !== false) {

        if (!$token)
            continue;

        if (($key = array_search((int)$token, $numbers)) === false)
            return false;
        else
            unset($numbers[$key]);

        $token = strtok(" ");
    }

    return true;
}

$string1 = "1 2 2 2";
$string2 = "2 1 2 1";

if (identStrings($string1, $string2)) {
    echo "These strings are identical!";
} else {
    echo "These strings are not identical...";
}
Sherif
  • 11,786
  • 3
  • 32
  • 57
1

just another solution using some different logic:

$str1 = "1 2 3 1";
$str2 = "1 1 3 2";

function sameStrings($str1, $str2)
{
    //check for the string lengths first
    if(strlen($str1) != strlen($str2))
        return false;

    $strArr = explode(' ', $str1);
    $occArr = array();

    //Get occurances of all numbers in the first string
    foreach($strArr as $str) $occArr[$str] = $occArr[$str]+1;

    //compare them with the second string, if the length of an of those numbers is not corrct then its false
    foreach($occArr as $num => $occ)
    {
        if(substr_count($str2, $num) != $occ)
            return false;
    }

    return true;
}

echo sameStrings($str1, $str2);
Desolator
  • 22,411
  • 20
  • 73
  • 96
0

you can put both strings into variable and sort it, then compare them .

0

See this solution PHP compare two string in random position without built-in sort function

<?php

function sort_array($arr){
  for($i=0; $i<count($arr); $i++){
    for($j=0; $j<count($arr)-1; $j++){
      if($arr[$j] > $arr[$j+1]){
        $temp = $arr[$j+1];
        $arr[$j+1] = $arr[$j];
        $arr[$j] = $temp;
      }
    }
  }
  return $arr;
}

function findShuffle($a, $b){
  $string_a = str_split($a);
  $string_b = str_split($b);
  $new_a = sort_array($string_a);
  $new_b = sort_array($string_b);
  if($new_a == $new_b){
    echo "Yes";
  }else{
    echo "No";
  }
  
  
}
$a = 'hello';
$b = 'llohe';
print_r(findShuffle($a, $b));
?>