Example of Associative Array in Javascript

Roy wanted to increase his typing speed for programming contests. So, his friend advised him to type the sentence “The quick brown fox jumps over the lazy dog” repeatedly, because it is a pangram. (Pangrams are sentences constructed by using every letter of the alphabet at least once.)

After typing the sentence several times, Roy became bored with it. So he started to look for other pangrams.

Given a sentence , tell Roy if it is a pangram or not.

E.g: We promptly judged antique ivory buckles for the next prize

function processData(input) {
    //Enter your code here
    var inpArr = input.split("");
    var uinput = input.toUpperCase();
    var freqObj = {};
    for (var a=65; a <= 90 ; a++) {
        var s = String.fromCharCode(a);
        freqObj[s] = 0;  // associative array as an object
    }
    
    for (var i = 0; i < uinput.length ; i++) {
        
        var char = uinput[i];
        //if (char in freqObj) {
        if ((char in freqObj) && (freqObj.hasOwnProperty(char)) ) {
            freqObj[char] = 1;
        } 
        
    }
    
    var okeys = Object.keys(freqObj);
    var sum = 0;
    for (var k = 0; k < okeys.length; k++) {
        if (freqObj.hasOwnProperty(okeys[k])) {
            sum += freqObj[okeys[k]];
        }
    }
    
    if (sum == 26) {
        console.log("pangram");
    } else {
        console.log("not pangram");
    }
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input);
});

PHP Reading from command line

$handle = fopen ("php://stdin","r");
// if single input (having no spaces)
fscanf($handle,"%d",$n);
// if trying to read 2 values separated by a space
fscanf($handle,"%d %s",$d,$s);
// if trying to read a string having spaces
$inp = trim(fgets($handle));

Advanced Features of PHP

1) Late Static Binding:
“Late binding” comes from the fact that static:: will not be resolved using the class where the method is defined but it will rather be computed using runtime information.

class A {
    public static function who() {
        echo __CLASS__;
    }
    public static function test() {
        self::who();
    }
}

class B extends A {
    public static function who() {
        echo __CLASS__;
    }
}

B::test();

Instead of “self::who()” replace with “static::who()”. Then the output will be “B” instead of “A”.

2) Variable Length Argument Lists :

func_num_args() ==> returns number of arguments passed
func_get_arg(int) ==> returns the nth argument passed in
func_get_args() ==> returns an array of all arguments

New Features in PHP 7

https://blog.feryn.eu/php-7-is-now-available-new-features-improvements/

1) Speed

2) Type Declarations:
Since PHP 5, you can use type hinting to specify the expected data type of an argument in a function declaration, but only in the declaration.  Besides only being used in function declarations, we were also limited to basically 2 types. A class name or an array.  When you call the function, PHP will check whether or not the arguments are of the specified type. With PHP 7 we now have added Scalar types. Specifically: int, float, string, and bool.

function stringTest(string $string) {
    echo $string;
 }

Additionally, PHP 7 gives us the opportunity to enable strict mode on a file by file basis. We do this by declare(strict_types=1); at the top of any given file.

PHP 7 also supports Return Type Declarations which support all the same types as arguments. To specify the return type, we add a colon and then the type right before the opening curly bracket.

function getTotal(float $a, float $b) : float {

3) Error Handling :
In PHP 7, an exception will be thrown when a fatal and recoverable error occurs, rather than just stopping the script. Fatal errors still exist for certain conditions, such as running out of memory, and still behave as before by immediately stopping the script. An uncaught exception will also continue to be a fatal error in PHP 7. This means if an exception thrown from an error that was fatal in PHP 5 goes uncaught, it will still be a fatal error in PHP 7.

A big change in PHP 7 is the fact that errors are no longer raised the way they used to be raised. Errors now behave in a similar way as exceptions. This means that errors can now be caught in a try/catch block. You can catch both exceptions and errors as Throwables, but you can also catch errors as Error objects. We point out that other types of errors such as warnings and notices remain unchanged in PHP 7. Only fatal and recoverable errors throw exceptions.

interface Throwable
    |- Exception implements Throwable
        |- ...
    |- Error implements Throwable
        |- TypeError extends Error
        |- ParseError extends Error
        |- ArithmeticError extends Error
            |- DivisionByZeroError extends ArithmeticError
        |- AssertionError extends Error

Throwable may be used in try/catch blocks to catch both Exception and Error objects (or any possible future exception types). Remember that it is better practice to catch more specific exception classes and handle each accordingly. However, some situations warrant catching any exception (such as for logging or framework error handling). In PHP 7, these catch-all blocks should catch Throwable instead of Exception.

4) New Operators (Spaceship Operator, Null Coalesce Operator) :

Spaceship Operator (useful in sort algorithms, etc)

$compare = 2 <=> 1
2 < 1? return -1 2 = 1? return 0 2 > 1? return 1

the Null Coalesce Operator, is effectively the fabled if-set-or.
If $firstName is empty then set it to Guest.

$name = $firstName ??  "Guest";

Can be chained.

$name = $firstName ?? $username ?? $placeholder ?? “Guest”; 


5) Anonymous Classes :

Anonymous classes are useful when simple, one-off objects need to be created.

$util->setLogger(new class {
    public function log($msg)
    {
        echo $msg;
    }
});

http://blog.teamtreehouse.com/5-new-features-php-7

6) Closure:Call() Method:

Closures are anonymous functions that are declared inline and assigned to a variable. It can be used as a callback for later execution. In PHP 5 it was already possible to bind an object to the scope of the closure as if it was a method.

The “call” method is one of the PHP 7 features that was introduced to simplify the process.

Given a sequence of words, print all anagrams together

$sortFunc = function($val) {
   $strArr = str_split($val);
   sort($strArr);
   return implode("", $strArr);
};

$arr = array("cat", "dog", "tac", "god", "act");

$words = array();
$index = array();

// form a new array with each string sorted within itself
$words = array_map($sortFunc, $arr);
// form a index array in order to remember original index
foreach ($words as $key => $val) {
    $index[$key] = $val;
}
asort($index);  // sort the values but maintain index association
foreach ($index as $key => $val) {
    // use index value in the original array to print
    echo $arr[$key] . "\n";
}

http://www.geeksforgeeks.org/given-a-sequence-of-words-print-all-anagrams-together/

Interesting Algorithm Interview Questions

1) Sorting a list of words such anagrams are grouped together. (Soundhound.com)
Input: [‘abc’,’test’,’vac’, ‘bac’, ‘london’, ‘cba’, ‘cav’, ‘lon’, ‘pst’]
Output: [‘abc’, ‘bac’, ‘cba’, ‘vac’, ‘cav’, ‘london’, ‘test’, ‘lon’, ‘pst’]

2. Design Twitter algorithm to retrieve top 10 new feeds (Soundhound.com)

Stored Procedure vs Function in MySQL

* Stored Procedures are pre-compile objects which are compiled for first time and its compiled format is saved which executes whenever it is called. But Function is compiled and executed every time when it is called.
Stored

* Procedures are used as scripts and functions are used as methods

* Functions have a scalar return value. Procedures do not have a return value.

* A stored procedure may have arguments that are IN, OUT, or INOUT. Functions may only have IN arguments.

* To invoke a stored procedure, use the CALL statement. To invoke a stored function, refer to it in an expression

Find a substring within a string and return the index where it was found


$bigString = "I am a really big realtor in the bay area";
$pattern = "realtor";

$i = 0;
$j = 0;
$bigStringLen = strlen($bigString);
$patternLen = strlen($pattern);
$found = false;
while ($i <= ($bigStringLen - $patternLen)) {
   if ($bigString[$i] == $pattern[$j]) {

   } else {
       $j=0;
   }
   $i++; $j++;
   if ($j >= $patternLen) {
       $found = true;
       break;
   }
}
if ($found) {
    print "found at " . ($i-$patternLen) . "\n";
} else {
    echo "\nnot found\n";
}