Categories
General

Phone Numbers

<?php

class Solution {

    private $hasmapExistingLetters;
    private $phoneKeyPad =
        array(
            1 => [],
            2 => ['a','b','c'],
            3 => ['d','e','f'],
            4 => ['g','h','i'],
            5 => ['j','k','l'],
            6 => ['m','n','o'],
            7 => ['p','q','r','s'],
            8 => ['t','u','v'],
            9 => ['w','x','y','z']
        );

    public function __construct(string $phonenumber){
        $this->hasmapExistingLetters = $this->buildHashmap($phonenumber);
        // var_dump($this->hasmapExistingLetters);
    }

    #364
    public function buildHashmap(string $phonenumber ) {
        $phonenumber = str_split($phonenumber);

        foreach ($phonenumber as $index => $singleDigit) {

            # singleDigit = 3 inex =0    
            $letters = $this->phoneKeyPad[$singleDigit];
            #letters =    ['d','e','f'],


            foreach ($letters as $letter){
                #hasmapExistingLetters['d'] = 0;   
                #hasmapExistingLetters['e'] = 0;   
                #hasmapExistingLetters['f'] = 0;   

                #hasmapExistingLetters['m'] = 1;   
                #hasmapExistingLetters['n'] = 1;   
                #hasmapExistingLetters['o'] = 1;   

                #hasmapExistingLetters['g'] = 2;   
                #hasmapExistingLetters['h'] = 2;   
                #hasmapExistingLetters['i'] = 2;   
                //var_dump($letter);
                $hasmapExistingLetters[$letter] = $index;
            }
        }

        // var_dump($hasmapExistingLetters);
        return $hasmapExistingLetters;
    }


    public function returnValidWords( array $validWordsInput) : array {

        foreach ($validWordsInput as $word) {
            #dog
            $validWord = true;
            //var_dump($wordToDissect);
            $len = strlen($word);
            for ($index=0; $index < $len; $index++) {
                # 0 => d
                # 1 => o
                # 2 => g
                $letter = $word[$index];

                if(!array_key_exists($letter, $this->hasmapExistingLetters)
                    && $this->hasmapExistingLetters[$letter] !== $index) {
                    $validWord = false;
                }
            }

            if($validWord === true)
                $resultValidWord[] = $word;
        }
        return $resultValidWord;
    }
}



$phoneNumber = '364';

$validWords =
    array('dog','fog','fish','water');

$solution = new Solution($phoneNumber);

$result = $solution->returnValidWords($validWords);

var_dump($result);




#build hasmap

#each validwords
#iterate through each letter
#check if ! exist in hasmap && index === validWord -> index
#return false
#return true

#resultValidword [] = theword

#return resultValidword;
#var_dump($phoneKeyPad);

Leave a Reply