skip to Main Content

Question: A string is given which will contain single digit numbers, letters, and question marks, and you have to check that string contains ??? between every pair of two numbers and their sum needs to be 10. If so then return true otherwise return false.

Understand it with the example:

a) arrb6???9xxbl5???eee5: true [because each pair contains `???` and the sum of any 2 pair digits are 10, (10!= 6+9 but 10 == 5+5)]

b) arrb6???9xxbl5???eee9: false [because each pair contains `???` but the sum of any 2 pair digits are not 10, (10!= 6+9 and 10 != 5+9)]

c) arrb6???9xxbl5??eee59: false [because each pair doesn't contain `???`, so straightforward false]

The jQuery code is already written for it:

judearasu/questionMarks.js

The equivalent PHP code is required.

2

Answers


  1. Chosen as BEST ANSWER

    The equivalent PHP code is given below:

    function QuestionsMarks($str) {
      $numbers = [];
      $inputStrArr = $str;
      $numbersWithIndex = [];
    
      $result = false;
      for ($i = 0; $i < strlen($inputStrArr); $i++) {
        if ((int)$inputStrArr[$i]) {
            array_push($numbers,$inputStrArr[$i]);
            array_push($numbersWithIndex,['number'=> (int)$inputStrArr[$i],'index'=> $i]);
        }
      }
      
      for ($j = 0; $j < count($numbersWithIndex) - 1; $j++) {
        if ((int)$numbersWithIndex[$j]['number'] + (int)$numbersWithIndex[$j+1]['number'] === 10) {
          $result = true;
          $subStr = substr($inputStrArr,$numbersWithIndex[$j]['index']+1,$numbersWithIndex[$j + 1]['index']);
          
          $subStr = str_replace('/[a-zA-Z]/g','',$subStr);
         
          if (false === strpos($subStr,'???')) {
            $result = false;
            return false;
          }
        }
      }
      return $result;
    }
    

    Sample Output: https://3v4l.org/lv4so


  2. You can make use of the below regex that uses positive lookahead:

    /(d+)([^d]+)(?=(d+))/
    

    It basically means to match a set of digits and non-digit letters only if they are followed by a set of digits later. We can then process each pair of digits in their own captured groups and assert if ??? exists in our captured group of non-digit characters and that if digits add up to 10.

    <?php
    
     function isSum10($str){
        preg_match_all('/(d+)([^d]+)(?=(d+))/', $str, $matches);
        foreach($matches[1] as $idx => $val){
            if(intval($val) + intval($matches[3][$idx]) === 10){
                if(strpos($matches[2][$idx], '???') !== false){
                    return true;
                }
            }
        }
        
        return false;
    }
    

    Online Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search