Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, February 8, 2024

Hindi to English Learning (Version 2)

Username: 

Password: 



Try: ashish/monkey

अध्याय चुनें:

इन वाक्यों को हिंदी से अंग्रेजी में बदलें:

Sentence:




Thursday, December 28, 2023

Coding Round in Interview for Data Scientist Role at a Bank (17 Nov 2023)

Task 1

Write a function: def solution(A) that, given an array A of N integers, returns the smallest positive integer (greater than 0) that does not occur in A. For example, given A = [1, 3, 6, 4, 1, 2], the function should return 5. Given A = [1, 2, 3], the function should return 4. Given A = [−1, −3], the function should return 1. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..100,000]; each element of array A is an integer within the range [−1,000,000..1,000,000].

A brute-force solution to this problem that will fail the performance tests will look like this:

def solution(A): # a_sort = sorted(A) rtn = -1 for i in range(1, 100001): if i in A: # This is the most time consuming instruction of this code that runs repeatedly for all of i(s) continue else: rtn = i break return rtn

Task 2

Task 3

Fig 3.1
Fig 3.2
Fig 3.3

Monday, December 25, 2023

Building a Tree from a BODMAS Expression (An exercise in Recursion)

There is an expression with N variables as in A, B, C, X, Y, Z. Note that variables do not repeat. And N-1 variables which can be +,-,*, and /

For example:

Ex 1: X + Y * Z
Ex 2: X - Y * Z + A
Ex 3: X * Y - Z / A
Ex 4: X / Y / Z
Ex 5: X * Y / Z
Ex 6: Z - Y + X 

Now, can you give me a recursion based JavaScript code to create a tree with operators on non-leaf nodes and leaf nodes contains the variables based on the BODMAS evaluation of the expression.

Code Pre-read

Certainly! To represent an expression as a tree structure in JavaScript, you can use a recursive data structure. Here's a simple example of how you can create a tree with operators on non-leaf nodes and variables on leaf nodes based on BODMAS evaluation:

Code in on next slide

This code defines a TreeNode class to represent nodes in the expression tree. The buildExpressionTree function takes an expression as input and returns the root of the expression tree. The tree is built recursively based on the BODMAS rules, with operators on non-leaf nodes and variables on leaf nodes.

Note: This code assumes that the input expression is properly formatted and follows BODMAS rules.

Code to Build a Tree Node

class TreeNode {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
} 

Code

function buildExpressionTree(expression) {
  // Tokenize Expression
  const tokens = expression.split(/\s/).filter(token => token.trim() !== ''); 

    
    // Helper function to build the expression tree recursively
    function buildTree(start, end) {
        if (start === end) {
            // Base case: single variable
            return new TreeNode(tokens[start]);
        }

        // Find the operator with the lowest precedence
        let minPrecedence = Infinity;
        let minIndex = -1;
        
        for (let i = start; i < end; i++) {
            if (tokens[i] === '+' || tokens[i] === '-') {
                const precedence = 1;
                if (precedence <= minPrecedence) {
                    minPrecedence = precedence;
                    minIndex = i;
                }
            } else if (tokens[i] === '*' || tokens[i] === '/') {
                const precedence = 2;
                if (precedence <= minPrecedence) {
                    minPrecedence = precedence;
                    minIndex = i;
                }
            }
        }
// Create the current node with the operator
        const currentNode = new TreeNode(tokens[minIndex]);

        // Recursively build left and right subtrees
        currentNode.left = buildTree(start, minIndex - 1);
        currentNode.right = buildTree(minIndex + 1, end);

        return currentNode;
    }

    // Build the tree starting from the root
    return buildTree(0, tokens.length - 1);
}

// Example usage:
const expression = "X + Y * Z";
const expressionTree = buildExpressionTree(expression);
console.log(expressionTree);

Explanation of the code

Certainly! Let's go through the code line by line:

TreeNode Class

class TreeNode {
    constructor(value) {
        this.value = value;
        this.left = null;
        this.right = null;
    }
}

This part defines a TreeNode class, which will be used to represent nodes in the expression tree. Each node has a value (either an operator or a variable), a left child, and a right child.
function buildExpressionTree(expression) {
    const tokens = expression.split(/\s/).filter(token => token.trim() !== ''); // Tokenize expression

    The buildExpressionTree function takes an input expression and splits it into tokens using a regular expression. The regular expression \b matches word boundaries, and filter is used to remove any empty or whitespace-only tokens.


    // Helper function to build the expression tree recursively
    function buildTree(start, end) {
        if (start === end) {
            // Base case: single variable
            return new TreeNode(tokens[start]);
        }

    The buildTree function is a helper function for building the expression tree recursively. The base case checks if start and end are the same, which means we have reached a leaf node containing a single variable. In this case, a new TreeNode is created with the variable as its value.

Operator Precedence Next, we are going to look at operator precedence. Viz: In the order DM > AS And if it’s DD or MM or DM, then left to right. // Find the operator with the lowest precedence let minPrecedence = Infinity; let minIndex = -1; for (let i = start; i < end; i++) { if (tokens[i] === '+' || tokens[i] === '-') { const precedence = 1; if (precedence <= minPrecedence) { minPrecedence = precedence; minIndex = i; } } else if (tokens[i] === '*' || tokens[i] === '/') { const precedence = 2; if (precedence <= minPrecedence) { minPrecedence = precedence; minIndex = i; } } } This part of the code searches for the operator with the lowest precedence in the given range (start to end). It iterates through the tokens, updating minPrecedence and minIndex whenever it finds an operator with lower precedence.

// Create the current node with the operator const currentNode = new TreeNode(tokens[minIndex]); // Recursively build left and right subtrees currentNode.left = buildTree(start, minIndex - 1); currentNode.right = buildTree(minIndex + 1, end); return currentNode; } Once the operator with the lowest precedence is found, a new TreeNode is created with that operator as its value. The left and right children of this node are then recursively built using the buildTree function. // Build the tree starting from the root return buildTree(0, tokens.length - 1); } Finally, the buildExpressionTree function initiates the construction of the expression tree by calling buildTree with the entire range of tokens. The function returns the root of the expression tree. // Example usage: const expression = "X + Y * Z"; const expressionTree = buildExpressionTree(expression); console.log(expressionTree); This part demonstrates the usage of the code by creating an example expression ("X + Y * Z") and building an expression tree from it. The resulting tree is then printed to the console. The example expression can be replaced with other expressions as needed. Overall, this code recursively builds an expression tree based on the BODMAS rules, where operators are placed on non-leaf nodes and variables on leaf nodes.

Prompts we tried on ChatGPT

There is an expression with N variables as in A, B, C, X, Y, Z. And N-1 variables which can be +,-,*, and /

For example:

Ex 1: X + Y * Z
Ex 2: X - Y * Z + A
Ex 3: X * Y - Z / A
Ex 4: X / Y / Z
Ex 5: X * Y / Z
Ex 6: Z - Y + X 

A problem can have from 1 to 5 operators.

Now, can you give me a recursion based Python code to create a BODMAS based parenthesized expression for the given expression.

Monday, December 11, 2023

Combinations of a set of alphabets using JavaScript (A problem of recursion)

Problem

Write a function that takes two parameters:
A: a list of distinct alphabets
n: a number that denotes the size of the selection we are going to make of the alphabets from the list A

The output of the function should be a list of lists containing all the possible combinations of size n from the list of alphabets A.

For example:
solution(['A', 'B', 'C', 'D'], 2)
Produces:

[
    [ 'A', 'B' ],
    [ 'A', 'C' ],
    [ 'A', 'D' ],
    [ 'B', 'C' ],
    [ 'B', 'D' ],
    [ 'C', 'D' ]
]
/*
Example 1:

Combinations ([A,B,C,D], 3) is equal to:
A + Combinations([B,C,D], 2) and
B + Combinations([C,D], 2)

~~~

Example 2:

Combinations(ABCDE, 3) is equal to:
A + Combinations(BCDE, 2) and
B + Combinations(CDE, 2) and
C + Combinations(DE, 2)

~~~

Example 3:

Combinations(ABCDE, 2) is equal to:
A + Combinations(BCDE, 1) and
B + Combinations(CDE, 1) and
C + Combinations(DE, 1) and
D + Combinations(E, 1)

*/

function solution(A, n) {
    if (A.length == 1 || A.length == n) { 
        return [A]; 
    } else if (n == 1) {        
        return A.map(function (i){ return [i] });
    }
    
    const resultArr = []
    for (let i = 0; i < A.length - n + 1; i++) {
        let currentElement = A[i]

        otherElements = A.slice(i+1)
        subCombinations = solution(otherElements, n-1)
        
        for (let j = 0; j < subCombinations.length; j++) {
            
            resultArr.push([currentElement].concat(subCombinations[j]))
        }
    }

    return resultArr
}

console.log(solution(['A', 'B', 'C', 'D'], 2))
console.log("~~~")

console.log(solution(['A', 'B', 'C', 'D'], 3))
console.log("~~~")

console.log(solution(['A', 'B', 'C', 'D', 'E'], 2))
console.log("~~~")


console.log(solution(['A', 'B', 'C', 'D'], 4))
console.log("~~~")

console.log(solution(['A', 'B', 'C', 'D'], 1))
console.log("~~~")

/*
[
    [ 'A', 'B' ],
    [ 'A', 'C' ],
    [ 'A', 'D' ],
    [ 'B', 'C' ],
    [ 'B', 'D' ],
    [ 'C', 'D' ]
]
~~~
[
    [ 'A', 'B', 'C' ],
    [ 'A', 'B', 'D' ],
    [ 'A', 'C', 'D' ],
    [ 'B', 'C', 'D' ]
]
~~~
[
    [ 'A', 'B' ], [ 'A', 'C' ],
    [ 'A', 'D' ], [ 'A', 'E' ],
    [ 'B', 'C' ], [ 'B', 'D' ],
    [ 'B', 'E' ], [ 'C', 'D' ],
    [ 'C', 'E' ], [ 'D', 'E' ]
]
~~~
[ [ 'A', 'B', 'C', 'D' ] ]
~~~
[ [ 'A' ], [ 'B' ], [ 'C' ], [ 'D' ] ]
~~~

*/

Permutations of a set of alphabets using JavaScript (A problem of recursion)

Problem

In the given problem statement we are asked to generate every possible permutation of the array given as input by the in JavaScript going from brute force method to optimized solution. What is Permutation of Array in JavaScript? Permutation of Array refers to the shuffling and ordering of elements present in an array. It generates all possible ways or arrangements of elements using the array as input source of it. If we have an array of n elements in javascript, it generates n! possible ways to order and output elements. The permutation of elements is the core of solving problem statement where the input and output can be visualized as follows : const arr = [ 1 , 2 , 3 ] ; // generate all permutations [ 1 , 2 , 3 ] [ 1 , 3 , 2 ] [ 2 , 1 , 3 ] [ 2 , 3 , 1 ] [ 3 , 1 , 2 ] [ 3 , 2 , 1 ]

Solution

function solution(A) { let resultArr = [] if (A.length > 1) { for (let i = 0; i < A.length; i++) { const currentElement = A[i]; otherElements = A.slice(0,i).concat(A.slice(i+1)); subPermutations = solution(otherElements); for (let j = 0; j < subPermutations.length; j++) { resultArr.push([currentElement].concat(subPermutations[j])); } } } else if(A.length == 1) { return [A] } return resultArr } console.log(solution(['A', 'B']))
[ Ref ]

Monday, October 2, 2023

Regular Expressions Quiz (12 Questions)


    
Question ()


            
            

            
 
 

Your score is:




Question:


                

                

Sunday, October 1, 2023

20 Quiz Questions For JavaScript Beginners with Easy Difficulty (Oct 2023)


    
Question ()


            
            

            
 
 

Your score is:




Question:


                

                

Sunday, April 9, 2023

Introduction to Sets (Also an exercise in Data Visualization)

What are sets?

Definition 1 (from NCERT) A set is a well-defined collection of objects. The following points may be noted : (i) Objects, elements and members of a set are synonymous terms. (ii) Sets are usually denoted by capital letters A, B, C, X, Y, Z, etc. (iii) The elements of a set are represented by small letters a, b, c, x, y, z, etc. Some examples of sets: (i) Odd natural numbers less than 10, i.e., 1, 3, 5, 7, 9 (ii) The rivers of India (iii) The vowels in the English alphabet, namely, a, e, i, o, u (iv) Various kinds of triangles (v) Prime factors of 210, namely, 2,3,5 and 7 (vi) The solution of the equation: x2 – 5x + 6 = 0, viz, 2 and 3. We give below a few more examples of sets used particularly in mathematics, viz. N : the set of all natural numbers Z : the set of all integers Q : the set of all rational numbers R : the set of real numbers Z+ : the set of positive integers Q + : the set of positive rational numbers, and R + : the set of positive real numbers. Definition 2 Sets: grouping of elements and each element in the group is unique.

Two basic types of sets: Overlapping sets and Non-overlapping sets.

Overlapping Sets

If there is one or more element present in both sets, the sets are called to be overlapping.

Example of Overlapping Sets

Set1: First six natural numbers.
Set2: First three natural numbers and first three alphabets.
Now two sets together in a Venn Diagram.
set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:

Example of Non-Overlapping Sets

Non-overlapping sets are better known as Disjoint Sets.

Set1: First six natural numbers.
Set2: First six alphabets.
Now two sets together in a Venn Diagram.
set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:

Nomenclature for sets that are 'Overlapping'

Subset and Superset Relation

If each element of set A is in set B, and also we have some extra elements present in set B which are not in set A: Then, we call set A a subset and set B a superset. A superset has more number of elements than a subset. Set1: Letters from the word 'Rhythm'.
Set2: English Consonants.
Now two sets together in a Venn Diagram.
set1 - set2 Intersection set2 - set1
Set1 Size:
Diff Size:
Intersection Size: Set2 Size:
Diff Size:

Equal Sets

If superset and subset have same number of elements, such that the two sets are fully overlapping each other then we call them 'Equal Sets'.
Tags: Mathematical Foundations for Data Science,JavaScript,Technology,

Tuesday, April 4, 2023

Brief Intro to Functions in JavaScript (Lesson 3)

Learning JavaScript as a Second Language

Functions in JavaScript

Four Parts of a Function

Function objects are created with function literals: // Create a variable called add and store a function in it that adds two numbers. var add = function (a, b) { return a + b; }; A function literal has four parts. The first part is the reserved word function. The optional second part is the function’s name. The function can use its name to call itself recursively. The name can also be used by debuggers and development tools to identify the function. If a function is not given a name, as shown in the previous example, it is said to be anonymous. The third part is the set of parameters of the function, wrapped in parentheses. Within the parentheses is a set of zero or more parameter names, separated by commas. These names will be defined as variables in the function. Unlike ordinary variables, instead of being initialized to undefined, they will be initialized to the arguments supplied when the function is invoked. The fourth part is a set of statements wrapped in curly braces. These statements are the body of the function. They are executed when the function is invoked.

Invocation

Invoking a function suspends the execution of the current function, passing control and parameters to the new function. In addition to the declared parameters, every function receives two additional parameters: this and arguments. The this parameter is very important in object oriented programming, and its value is determined by the invocation pattern. There are four patterns of invocation in JavaScript: 1. the method invocation pattern, 2. the function invocation pattern, 3. the constructor invocation pattern, and 4. the apply invocation pattern. The patterns differ in how the bonus parameter “this” is initialized. The invocation operator is a pair of parentheses that follow any expression that produces a function value. The parentheses can contain zero or more expressions, separated by commas. Each expression produces one argument value. Each of the argument values will be assigned to the function’s parameter names. There is no runtime error when the number of arguments and the number of parameters do not match. If there are too many argument values, the extra argument values will be ignored. If there are too few argument values, the undefined value will be substituted for the missing values. There is no type checking on the argument values: any type of value can be passed to any parameter.

Out of these four patterns, "Method Invocation Pattern" and "Constructor Invocation Pattern" are important in understanding and working with KnockoutJS.

The Method Invocation Pattern

When a function is stored as a property of an object, we call it a method. When a method is invoked, “this” variable is bound to that object. If an invocation expression contains a refinement (that is, a . dot expression or [subscript] expression), it is invoked as a method: // Create myObject. It has a value and an increment method. The increment method takes an optional parameter. If the argument is not a number, then 1 is used as the default. var myObject = { value: 0, increment: function (inc) { this.value += typeof inc === 'number' ? inc : 1; } }; myObject.increment( ); document.writeln(myObject.value); // 1 myObject.increment(2); document.writeln(myObject.value); // 3 A method can use this to access the object so that it can retrieve values from the object or modify the object. The binding of this to the object happens at invocation time. This very late binding makes functions that use this highly reusable. Methods that get their object context from this are called public methods.

The Constructor Invocation Pattern

JavaScript is a prototypal inheritance language. That means that objects can inherit properties directly from other objects. The language is class-free. This is a radical departure from the current fashion. Most languages today are classical. Prototypal inheritance is powerfully expressive, but is not widely understood. JavaScript itself is not confident in its prototypal nature, so it offers an object-making syntax that is reminiscent of the classical languages. Few classical programmers found prototypal inheritance to be acceptable, and classically inspired syntax obscures the language’s true prototypal nature. It is the worst of both worlds. If a function is invoked with the new prefix, then a new object will be created with a hidden link to the value of the function’s prototype member, and this will be bound to that new object. The new prefix also changes the behavior of the return statement. Functions that are intended to be used with the new prefix are called constructors. By convention, they are kept in variables with a capitalized name. If a constructor is called without the new prefix, very bad things can happen without a compile-time or runtime warning, so the capitalization convention is really important. Use of this style of constructor functions is not recommended. // Create a constructor function called Quo. It makes an object with a status property. var Quo = function (string) { this.status = string; }; // Give all instances of Quo (called a Class in classical programming like C++) a public method called get_status. Quo.prototype.get_status = function ( ) { return this.status; }; // Make an instance of Quo. var myQuo = new Quo("confused");

Return Statement

When a function is invoked, it begins execution with the first statement, and ends when it hits the } that closes the function body. That causes the function to return control to the part of the program that invoked the function. The return statement can be used to cause the function to return early. When return is executed, the function returns immediately without executing the remaining statements. A function always returns a value. If the return value is not specified, then undefined is returned. If the function was invoked with the new prefix and the return value is not an object, then this (the new object) is returned instead.

Exception Handling

JavaScript provides an exception handling mechanism. Exceptions are unusual (but not completely unexpected) mishaps that interfere with the normal flow of a program. When such a mishap is detected, your program should throw an exception: The throw statement interrupts execution of the function. It should be given an exception object containing a name property that identifies the type of the exception, and a descriptive message property. You can also add other properties. The exception object will be delivered to the catch clause of a try statement: If an exception is thrown within a try block, control will go to its catch clause. A try statement has a single catch block that will catch all exceptions. If your handling depends on the type of the exception, then the exception handler will have to inspect the name to determine the type of the exception.

Recursion

A recursive function is a function that calls itself, either directly or indirectly. Recursion is a powerful programming technique in which a problem is divided into a set of similar subproblems, each solved with a trivial solution. Generally, a recursive function calls itself to solve its subproblems. Example: Factorial Problem (n!)
Tags: Technology,JavaScript,