Twin Identical Challenge

Problem :There was a problem to find identical string after changing character

Rule

1: you can shuffle even indexed character to even index character
2: you can shuffle odd indexed character to odd index character

eg: “asdf” and “dsaf” are identical while “asdf” and “sadf” are not!

Solution (PHP)

function twins($a, $b) {
    $return = array();
    $max = count($a) > count($b) ?count($a):count($b);
    for($i=0; $i <$max; $i++ ){
        
        if(!isset($a[$i]) ||  !isset($b[$i]) || (strlen($a[$i]) != strlen($b[$i]))){
            $return[$i] = 'NO';
        }else{
            // now do the logic for the suffling
            $basestring = $a[$i];
            $comparestring = $b[$i];
            $matched = TRUE;
            for($j=0; $j< strlen($basestring); $j++){
                if($basestring[$j] == $comparestring[$j]){
                    continue;
                }else{
                    $matched = FALSE;
                    // now  figure out what is the character and is it avialble for exchange on that type of index
                    for($k=$j+2;$k<strlen($basestring); $k=$k+2){
                        if ($basestring[$k] == $comparestring[$j]){
                            // matched then swipe the original one
                            $matched = TRUE;
                            $tmp = $basestring[$j];
                            $basestring[$j] = $basestring[$k];
                            $basestring[$k] = $tmp;
                            unset($tmp);
                        }else{
                            break;
                            // can not match further
                        }
                        
                    }
                    // check the logic here
                }
            }
            
            if($matched){
                $return[$i] = 'YES';
                
            }else{
                $return[$i] = 'NO';
            }
        }
        
        // now do the shit
    }
    return $return;
}

// testing part!
$string1 = array("a","asdf","abc","asasas","asaas");
$string2 = array("a",'afds','acdv','aassfd','aaass','adad');
$result = twins($string1, $string2);
echo implode("\n", $result);

developerCK

An E-learning Solution Designer, Technical enthusiastic, LAMP Stack Developer - http://about.developerck.com

Leave a Reply

Your email address will not be published. Required fields are marked *