Tries: Contacts

  • + 0 comments

    Anyone knows why the same logic implemented with array and object have different results in PHP?

    <?php
    
    $n = intval(trim(fgets(STDIN)));
    
    // $trie = [[], 0];
    // 
    // function addToTrie(array &$node, string $s, int $idx) 
    // {
    //     if ($idx === strlen($s)) {
    //         return;
    //     }
    //     $key = $s[$idx];
    //     if (!isset($node[0][$key])) {
    //         $node[0][$key] = [[], 0];
    //     } 
    //     $node[0][$key][1] ++;
    //     addToTrie($node[0][$key], $s, $idx+1);
    // }
    // 
    // function readFromTrie(array $node, string $s): int
    // {
    //     foreach (str_split($s) as $key) {
    //         if (!isset($node[0][$key])) {
    //             return 0;
    //         }
    //         $node = $node[0][$key];
    //     }
    //      return $node[1];
    // }
    
    class Node {
        public $children = [];
        public $count = 0;
    }
    
    $trie = new Node;
    
    function addToTrie(Node $node, string $s, int $idx)
    {
        if ($idx === strlen($s)) {
            return;
        }
        $key = $s[$idx];
        if (!isset($node->children[$key])) {
            $node->children[$key] = new Node;
        } 
        $node->children[$key]->count ++;
        addToTrie($node->children[$key], $s, $idx+1);
    }
    
    function readFromTrie(Node $node, string $s)
    {
       foreach (str_split($s) as $key) {
           if (!isset($node->children[$key])) {
               return 0;
           }
           $node = $node->children[$key];
       }
        return $node->count;
    }
    
    for ($n_itr = 0; $n_itr < $n; $n_itr++) {
        $first_multiple_input = explode(' ', rtrim(fgets(STDIN)));
    
        $op = $first_multiple_input[0];
    
        $contact = $first_multiple_input[1];
        
        
        if ($op === 'add') {
           addToTrie($trie, $contact, 0);
        } elseif ($op === 'find') {
           echo readFromTrie($trie, $contact) . PHP_EOL;
        }
    }