0% found this document useful (0 votes)
38 views

JS, DS & Algo

JavaScript Data structure and algorithms pdf

Uploaded by

prabhat7660403
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views

JS, DS & Algo

JavaScript Data structure and algorithms pdf

Uploaded by

prabhat7660403
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 24

JS, DS & Algo

JS, DS & Algo

// function minimumBribes(arr) {
// let n = arr.length;
// let check = true;
// let count = 0;
// while(check) {
// check=false;
// for(let i=0; i<n-1; i++) {
// let init = arr[i];
// if(init !== i+1) {
// let index = init-1;
// let temp = init;
// arr[i] = arr[index];
// arr[index] = temp;
// count++;
// check=true;
// }
// }
// }
// console.log(“-------“, count);
// return count;
// }

// minimumBribes([1,3,5,2,4,6,7]);
//minimumBribes([10,9,2,7,4,5,1,3,8,6]);
//minimumBribes([2,1,3,4,5,6,7,8]);
//minimumBribes([8,4,1,3,2,7,6,5]);
//minimumBribes([7,1,3,2,4,5,6]);

// function arrayManipulation(n, queries) {


// const arr = [];
// let len = queries.length;
// let max=0, sum=0;
// for(let i=0; i<len; i++) {
// let a = queries[i][0];
// let b = queries[i][1];
// let k = queries[i][2];
// arr[a] = arr[a] ? arr[a] + k : k;
// if (b+1 <= n) {
// arr[b+1] = (arr[b+1] ? (arr[b+1] - k) : -k);
// }
// }

// for(let i=0; i<arr.length; i++) {


// sum += (arr[i] || 0);
// max = Math.max(max, sum);
// }
// console.log(“---“, arr, max);
// return max;
// }

//arrayManipulation(4, [[2,3,603],[1,1,286],[4,4,882]]);
//arrayManipulation(10, [[1,5,3],[4,8,7],[7,9,1]]);

// ------------------------------------------------------------------------------------------------------------------
/* 1. Anagram */
// Function to create anagrams
// 1 ≤ n ≤ 105
// s consists of digits only.
// The length of s is a multiple of 2.

// function getAnagram (s) {


// const str = s.toString();
// const len = str.length;
// const first = str.substr(0, len/2);
// const second = str.substr(-(len/2), len/2);
// let count = 0;
// console.log(“---first---“, first);
// console.log(“---Second---“, second);
// for(let i=0; i<len/2; i++) {
// if(!second.includes(first[i])) {
// count++;
// console.log(“-----“, count);
// }
// }
// console.log(“The minimum change required”, count);
// return count;
// }

// getAnagram(“123456");
//getAnagram(“12346392”);

/* 2. Find Vowels */
// strArr = [‘aba’,‘bcb’,‘ece’,‘aa’,‘e’]
// queries = [‘1-3’,‘2-5’,‘2-2’]
// result [2, 3, 0]
// 1 ≤ n, q ≤ 105
// 1 ≤ l ≤ r ≤ n
// 1 ≤ size of strArr[i] ≤ 10
// Determine how many strings starting from index l and ending at index r have vowels as the
first and last character

// function hasVowels (strArr, query) {


// const vowels = [‘a’,‘e’,‘i’,‘o’,‘u’];
// const result = [];
// let i=0;
// while (i < query.length) {
// let count=0;
// for(let j=(query[i].split(“-”)[0])-1; j < query[i].split(“-”)[1]; j++) {
// console.log(“--strarr--“, strArr, strArr[j], j);
// const subLen = strArr[j].length;
// if(vowels.includes(strArr[j][0]) && vowels.includes(strArr[j][subLen-1])) {
// count++;
// }
// }
// i++;
// result.push(count);
// }
// console.log(“----RESULT------“, result);
// return result;
// }

// hasVowels([‘aba’,‘bcb’,‘ece’,‘aa’,‘e’], [‘1-3’,‘2-5’,‘2-2’]);
// hasVowels([ “aab”, “a”, “bcd”, “awe”, “bbbbbu” ], [ “2-3", “4-5” ]);
/*hasVowels([‘iti’, ‘muspubz’, ‘st’, ‘o’, ‘xlt’, ‘ezymvlfie’, ‘iwljxna’, ‘azdfb’, ‘esifhidtfu’, ‘kckaa’, ‘aksy’,
‘zxcbugpopu’,
‘aper’, ‘esgfudro’, ‘vjiug’, ‘crlqi’, ‘io’, ‘as’, ‘opljvcfloa’, ‘edjshci’, ‘eovyrii’, ‘oahslcvqpi’, ‘oqrukywi’,
‘omfffogte’, ‘rg’, ‘i’, ‘orzxj’, ‘epe’, ‘bvcgahwhc’, ‘iyabe’, ‘urto’, ‘bl’, ‘ie’, ‘umnkvlo’, ‘utsqxou’,
‘nsggxktwcx’,
‘etwqee’, ‘swl’, ‘okcylznu’, ‘ispawolji’, ‘klzo’, ‘mufay’, ‘odgu’, ‘oa’, ‘qgp’, ‘jjxuw’, ‘usxai’, ‘ao’, ‘m’,
‘avo’],
[‘33-43’, ‘38-41’, ‘21-44’, ‘11-22’, ‘43-50’, ‘16-23’, ‘5-24’, ‘30-32’, ‘28-38’, ‘19-29’, ‘32-43’, ‘19-33’,
‘9-13’, ‘15-46’, ‘39-43’,‘21-31’, ‘10-25’, ‘24-47’, ‘4-36’, ‘21-48’, ‘35-36’, ‘10-21’, ‘2-42’, ‘19-42’, ‘20-
41’, ‘33-40’, ‘1-8’, ‘16-16’, ‘17-30’, ‘7-11’, ‘24-33’, ‘40-49’, ‘15-42’, ‘45-45’, ‘17-50’, ‘34-45’, ‘5-15’,
‘43-46’, ‘18-34’, ‘8-15’, ‘6-6’, ‘8-41’, ‘6-15’, ‘23-33’, ‘35-37’, ‘11-40’, ‘17-29’, ‘9-11’, ‘7-43’, ‘5-44’])*/

// ---------------------------------------------------------------------------------------------------------------------
/* 3. Rods cutting */
// Given an array with the lengths of various metal rods, repeatedly perform the following:
// Count the number of rods.
// Find the rod(s) with the shortest length.
// Discard any rod of that length.
// Cut that shortest length from each of the longer rods. These are offcuts.
// Discard all offcuts.
// Repeat until there are no more rods.

// function rodOffcut(arr) {
// const result = [];
// let smallest = 0;
// let len = 0;
// arr.sort((a,b) => a-b);
// while(arr && arr.length) {
// len = arr.length;
// result.push(len);
// smallest = arr[0];
// for (let i=0; i<len; i++) {
// arr[i] = arr[i] - smallest;
// }
// arr = arr.filter(item => {
// if(item > 0) {
// return item;
// }
// });
// }
// console.log(result);
// return result;
// }

// rodOffcut([1,1,3,4]);
// rodOffcut([5, 4, 4, 2, 2, 8]);

// ---------------------------------------------------------------------------------------------
// 4. Painting Graph
/* Digital graphics tools often make available a “bucket fill” tool that will only paint adjacent cells .
In one fill, a modified bucket tool recolors adjacent cells (connected horizontally or vertically but
not diagonally) that have the same color. Given a picture represented as a 2-dimensional array
of letters representing colors, find the minimum number of fills to completely repaint the picture.
*/
// picture= [“aabba”, “aabba”, “aaacb”]
// Each string represents a row of the picture and each letter represents a cell’s color.
// function strokesRequired(picture) {
// const obj = {};
// //const color1, color2, color3, color4, color5;
// const orgArr = picture.slice(0);
// while (picture.length) {
// const prev = (orgArr.length - (picture.length+1));
// const prevRow = prev ? orgArr[prev] : orgArr[0];
// const row = picture.shift();
// console.log()
// let len = row.length;
// for (let i = 0; i < len; i++) {
// // console.log(“----“, obj[row[i]], row[i], obj);
// let c = “color”;
// obj[c] = 0;
// if(!prev) {
// if (obj[c] && row[i] === row[i+1]) {
// obj[c] += 1;
// } else if(!obj[c]) {
// obj[c] = 1;
// } else {
// obj[c+1] = 1;
// }
// }
// else if() {

// }
// }
// }
// console.log(obj);
// return obj;
// }
// function strokesRequired(picture) {
// const orgArr = picture.slice(0);
// const obj = {};
// while(picture.length) {
// const prev = (orgArr.length - (picture.length+1));
// const prevRow = prev ? orgArr[prev] : orgArr[0];
// let row = picture.shift();
// let len = row.length;
// for (let i = 0; i < len; i++) {
// if(!prev) {
// while(row[i] === row[i+1]) {
// obj[row.substr(i, i+2)] = 1
// }
// }
// }
// }
// }
//strokesRequired([“aabba”, “aabba”, “aaacb”]);
////////////////////////////////////////////////////
/* String Question 1 */
// First Solution
// function makeAnagram (a, b) {
// const len = a.length >= b.length ? a.length : b.length;
// const alen = a.slice(0).length;
// const blen = b.slice(0).length;
// let c1 = ‘’;
// let count = 0;

// for(let i=0; i<len; i++) {


// if(b.indexOf(a[i]) !== -1) {
// c1 = c1.concat(a[i]);
// b = b.replace(a[i], “”);
// }
// }
// count = (alen + blen - 2*c1.length);
// //console.log(count);
// return count;
// }

// Second Solution
// function makeAnagram(a, b) {
// let counter = {};
// let total = 0;
// Array.from(a).forEach(char => {
// counter[char] = counter[char] || 0;
// counter[char]++;
// })
// // console.log(‘first’, counter);
// Array.from(b).forEach(char => {
// counter[char] = counter[char] || 0;
// counter[char]--;
// })
// // console.log(‘second’, counter);
// Object.keys(counter).forEach(k => {
// if (counter[k] !== 0) {
// total += Math.abs(counter[k]);
// }
// })
// return total;
// }

//makeAnagram(‘jxwtrhvujlmrpdoqbisbwhmgpmeoke’, ‘fcrxzwscanmligyxyvym’);
//makeAnagram(‘fcrxzwscanmligyxyvym’, ‘jxwtrhvujlmrpdoqbisbwhmgpmeoke’);
//makeAnagram(‘showman’, ‘woman’);
//makeAnagram(‘cde’, ‘abc’);
// -----------------------------------------------------------------------------------------------
// Maximum occuring element in an array
// function maxOccur (arr) {
// const obj = {};
// let max = 0;
// let key = [];
// arr.forEach(ele => {
// if(obj[ele]) {
// obj[ele] += 1;
// } else {
// obj[ele] = 1;
// }
// });
// Object.keys(obj).forEach(item => {
// if(obj[item] > max) {
// max=obj[item];
// }
// });
// Object.keys(obj).forEach(item => {
// if(obj[item] === max) {
// key.push(item);
// }
// })
// console.log(‘-----’, obj, max, key);
// return key;
// }

//maxOccur([1,1,1,2,2,2,2,3,4,5,5,5]);
//maxOccur([‘a’,‘a’,‘f’,‘r’,‘e’,‘e’,‘e’,‘e’,‘w’,‘w’,‘w’]);

/* String Question 2 */
// Delete matching adjcent characters
// SOLUTION 1
// function alternatingCharacters(s) {
// let str = s.slice(0).split(‘’);
// let len = s.length;
// let extra = [];

// for(let i=0; i<len; i++) {


// let elen = extra.length;
// if(elen && extra[elen -1] === str[i] && str[i] === str[i+1]) {
// extra.push(str[i]);
// } else if(str[i] === str[i+1]) {
// extra.push(str[i]);
// }
// }
// console.log(str, extra);
// return extra.length;
// }

//SOLUTION 2
// function alternatingCharacters (s) {
// let c=0;
// const len = s.length;

// for(let i=0; i<len; i++) {


// if(s[i] === s[i+1]){
// c++;
// }
// }
// console.log(“----“, c);
// return c;
// }
//alternatingCharacters(‘aaabbb’);
//alternatingCharacters(‘ababcccddd’);
//alternatingCharacters(‘abababababababab’);
//alternatingCharacters(‘ABABABABABABAAB’);

/* String Question 3 */
// Remove only one char to make letters of equal frequency
//aabbccddeefghi
//{‘a’: 2, ‘b’: 2, ‘c’: 2, ‘d’: 2, ‘e’: 2, ‘f’: 1, ‘g’: 1, ‘h’: 1, ‘i’: 1}
// Return YES if it is valid and NO if it is not valid
// function isValid(s) {
// const freq = {};
// let len = s.length;
// for(let i=0; i<len; i++) {
// if(freq[s[i]]) {
// freq[s[i]] += 1;
// } else {
// freq[s[i]] = 1;
// }
// }

// let arr = Object.values(freq).sort();


// let arlen = arr.length;
// let result = “”;
// const al = (arr.length%2 ===0) ? arr.length/2 : parseInt(arr.length/2)+1;
// let diff = 0;
// for(let i=0; i<al; i++) {
// diff += Math.abs(arr[i] - arr[arlen-(i+1)]);
// }
// console.log(“--“, freq, arr, diff);
// if(diff > 1) {
// if(Math.abs(arr[0] - arr[1]) === diff) {
// result = ‘YES’;
// } else {
// result = ‘NO’;
// }
// } else {
// result = ‘YES’;
// }
// console.log(“RESULT”, result);
// return result;
// }

//isValid(‘aabbccddeefghi’); //NO
//isValid(‘aaabbcc’); //YES
//isValid(‘abcdefghhgfedecba’); //YES
//isValid(‘xxxaabbccrry’);//NO
//
isValid(‘ibfdgaeadiaefgbhbdghhhbgdfgeiccbiehhfcggchgghadhdhagfbahhddgghbdehidbibaeaag
aeeigffcebfbaieggabcfbiiedcabfihchdfabifahcbhagccbdfifhghcadfiadeeaheeddddiecaicbgigccage
icehfdhdgafaddhffadigfhhcaedcedecafeacbdacgfgfeeibgaiffdehigebhhehiaahfidibccdcdagifgaiha
cihadecgifihbebffebdfbchbgigeccahgihbcbcaggebaaafgfedbfgagfediddghdgbgehhhifhgcedechah
idcbchebheihaadbbbiaiccededchdagfhccfdefigfibifabeiaccghcegfbcghaefifbachebaacbhbfgfddec
eababbacgffbagidebeadfihaefefegbghgddbbgddeehgfbhafbccidebgehifafgbghafacgfdccgifdcbbb
idfifhdaibgigebigaedeaaiadegfefbhacgddhchgcbgcaeaieiegiffchbgbebgbehbbfcebciiagacaiechdi
gbgbghefcahgbhfibhedaeeiffebdiabcifgccdefabccdghehfibfiifdaicfedagahhdcbhbicdgibgcedieihci
chadgchgbdcdagaihebbabhibcihicadgadfcihdheefbhffiageddhgahaidfdhhdbgciiaciegchiiebfbcbh
aeagccfhbfhaddagnfieihghfbaggiffbbfbecgaiiidccdceadbbdfgigibgcgchafccdchgifdeieicbaididhfcf
dedbhaadedfageigfdehgcdaecaebebebfcieaecfagfdieaefdiedbcadchabhebgehiidfcgahcdhcdhgc
hhiiheffiifeegcfdgbdeffhgeghdfhbfbifgidcafbfcd’);

/* String Question 4 */
// Getting all substrings
// Given string s=‘mnonopoo’
// All posible substrings {m,n,o,n,o,p,o,o,non,ono,opo,oo}
// S1=‘aaaa’
// substrings = {a,a,a,a,aa,aa,aa,aaa,aaa,aaaa}
// s2=‘abcbaba’
// substrings = {a,b,c,b,a,b,a,bcb,bab,aba}
// substrings are accepted only if all chars are same or only middle char is different

// function substrCount(n, s) {
// let arr = [];
// let i=2;
// while(i <= n) {
// for(let j=0; j<=n-i; j++) {
// console.log(“1st”, i, j);
// if(i <= 3 && s[j] === s[j+(i-1)]) {
// arr.push(s.substr(j, i));
// }
// if(i > 3) {
// let len = parseInt(i/2);
// let chlen = [...new Set(s.substr(j, len))].join().length;
// if(chlen === 1 && [...new Set(s.substr(j, len))].join() === [...new Set(s.substr(len+1,
len))].join()) {
// arr.push(s.substr(j, i))
// }
// }
// }
// i++;
// }
// console.log(“result”, arr, n+arr.length);
// return n+arr.length;
// }
/* PYTHON SOLUTION
def substrCount(n, s):
count = len(s)
for i, char in enumerate(s):
diff_char_idx = None
for j in range(i+1, n):
if char == s[j]:
if diff_char_idx is None:
count +=1
elif j - diff_char_idx == diff_char_idx - i:
count += 1
break
else:
if diff_char_idx is None:
diff_char_idx = j
else:
break
return count
*/
//substrCount(7, ‘abcbaba’);
//substrCount(4, ‘aaaa’);
//substrCount(8, ‘mnonopoo’);

// --------------------------------------------------------------------
/* String question 5 */
// Find the common substring which is a child of both s1 and s2 string
// you can’t rearrange the characters
// Return the length of the string
// Both string is of equal lenght
// s1=“HARRY”, s2=“SALLY” common=“AY”
//s1=“ABCD”, s2=“ABDC” common=“ABC” or “ABD”

// function commonChild(s1, s2) {


// let C = [];
// let len = s1.length;
// for(let i=0; i<len+1; i++) {
// C.push(Array(len+1).fill(0));
// }
// for (let i = 0; i < len; i++) {
// for (let j = 0; j < len; j++) {
// if (s1.charAt(i) == s2.charAt(j)) {
// C[i+1][j+1] = C[i][j] + 1;
// } else {
// C[i+1][j+1] = Math.max(C[i+1][j], C[i][j+1]);
// }
// }
// }
// console.log(“--“, C, C[s1.length][s2.length]);
// return C[s1.length][s2.length];
// }

//commonChild(“ABCD”, “ABDC”);
//commonChild(“HARRY”, “SALLY”);
//commonChild(“SHINCHAN”, “NOHARAAA”);
//commonChild(“NOHARAAA”, “SHINCHAN”);
// ------------------------------------------------------
// Counting valleys
// UDDDUDUU only count consecutive down (i.e. valleys)
// A mountain is a sequence of consecutive steps above sea level, starting with a step up from
sea level and ending with a step down to sea level.
// A valley is a sequence of consecutive steps below sea level, starting with a step down from
sea level and ending with a step up to sea level.
// function countingValleys(steps, path) {
// let sum = 0;
// let count = 0;
// for(let i=0; i<steps; i++){
// if(path[i]==‘U’){
// if(++sum==0) count++;
// }
// else sum--;
// console.log(“--sum”, sum, count);
// }
// return count;
// }
//countingValleys(8, ‘UDDDUDUU’) //1
//countingValleys(8, ‘DDUUUUDD’) //1
//countingValleys(12, ‘DDUUDDUDUUUD’) //2
// --------------------------------------------------------------

// Calling api using

// const axios = require(‘axios’);


// const // const https = require(‘https’);

// const agent = new https.Agent({


// rejectUnauthorized: false
// });

// async function getCountry(code) {


// const obj = {};
// const res = await axios.get(‘https://restcountries.eu/rest/v2/all’, { httpsAgent: agent })
// res.data.forEach(item => {
// obj[item.alpha2Code] = item.name;
// });
// console.log(obj[code]);
// return obj[code];
// }
// getCountry(‘FI’)

// function loadDoc() {
// var x
// xhttp.onreadystatechange = function() {
// if (this.readyState == 4 && this.status == 200) {
// console.log(this.responseText);
// }
// };
// xhttp.open(“GET”, “https://restcountries.eu/rest/v2/all”, true);
// xhttp.send();
// }

// const // const https = require(‘https’);


// const axios = require(‘axios’);
// const agent = new https.Agent({
// rejectUnauthorized: false
// });
//process.env[“NODE_TLS_REJECT_UNAUTHORIZED”] = 0;
//url: ‘https://jsonmock.hackerrank.com/api/football_matches?
year=2011&team1=Barcelona&page=1’
//https.get(‘https://jsonmock.hackerrank.com/api/football_matches?
year=2011&team2=Barcelona&page=1’
// function totalGoals () {
// axios.get(‘https://jsonmock.hackerrank.com/api/football_matches?
year=2011&team1=Barcelona&page=1’, { httpsAgent: agent })
// .then(res => console.log(res));

// axios.get(‘https://jsonmock.hackerrank.com/api/football_matches?
year=2011&team2=Barcelona&page=1’, { httpsAgent: agent })
// .then(res => console.log(res));
// }
// function callback1(data) {
// console.log(JSON.parse(“1”, data));
// }

// function callback2(data) {
// console.log(JSON.parse(“2", data));
// }
//totalGoals();

//
// Observe the following:
// Each letter is printed on a new line.
// Then the vowels are printed in the same order as they appeared in .
// Then the consonants are printed in the same order as they appeared in .
//javascriptloops
// function vowelsAndConsonants(s) {
// const str = s.split(‘’);
// const vowel = {a:1, e:1, i:1, o:1, u:1};
// const len = str.length;
// let v=[];
// let c=[];
// let finalStr=[];
// for(let i=0; i<len; i++) {
// if(vowel[str[i]]) {
// v.push(str[i]);
// }
// else {
// c.push(str[i]);
// }
// }
// finalStr = v.concat(c);
// for(let i=0; i<len; i++) {
// console.log(finalStr[i]);
// }
// }
// vowelsAndConsonants(‘javascriptloops’)
/*
* Declare a RegExp object variable named ‘re’
* It must match a string that starts and ends with the same vowel (i.e., {a, e, i, o, u})
*/
//const re = new RegExp(/^([aeiou]).*\1$/);

/* ---------------- Class Inheritance ------------------------ */


// class Rectangle {
// constructor(w, h) {
// this.w = w;
// this.h = h;
// //this.area = area;
// }
// // static area(a,b) {
// // return a*b;
// // }
// area() {
// return this.w*this.h;
// }
// }

// function area() {
// return this.w*this.h;
// }

// Rectangle.prototype.area = function area() {


// return this.w*this.h;
// }

// const square = new Rectangle(10,9);


// class Square extends Rectangle {
// area(){
// return this.w*this.h;
// }
// }
// class Square extends Rectangle {
// constructor(side){
// super();
// this.side=side;
// }
// area() {
// return this.side*this.side;
// }
// }
// const s = new Square(4);
// console.log(“Area Square: “, s.area());
// console.log(JSON.stringify(Object.getOwnPropertyNames(Square.prototype)));
// const child = new Square(2,4);
// const parent = new Square(3,4);
// console.log(“Child”, child.area());
// console.log(“parent”,parent.area());

/-------------- Object Literals -------------------/


// ‘use strict’;
// let lime = {
// type: ‘Mexican lime’,
// color: ‘green’,
// getInformation: function() {
// return ‘This ’ + this.type + ' is ' + this.color + ‘.’;
// }
// }

// console.log(lime.getInformation());

// lime.color = ‘yellow’;
// console.log(lime.getInformation());

/-----------------------Singleton Class Using a Function------------------------/


//Singleton Class Using a Function
// A singleton class is a design pattern that restricts a class to a single instance. When we
assign the value of new function(){...} to a variable, the following happens:

// We define an anonymous constructor function.


// We invoke the anonymous constructor function with the new keyword.
// ‘use strict’;
// let lime = new function() {
// this.type = ‘Mexican lime’;
// this.color = ‘green’;
// this.getInformation = function() {
// return ‘This ’ + this.type + ' is ' + this.color + ‘.’;
// };
// }

// console.log(lime.getInformation());

// lime.color = ‘yellow’;
// console.log(lime.getInformation());

/----------------- STATIC METHOD ---------------------/


/*Static methods are methods relevant to all instances of a class — not just any one instance.
These methods receive information from their arguments and not a class instance, which allows
us to invoke a class’ static methods without creating an instance of the class. In fact, we actually
can’t call a static method on an instantiated class object (attempting to do so throws a
TypeError).

We define a class’ static methods using the static keyword. We typically use these methods to
create utility functions for applications, as they can’t be called on class objects.*/

// ‘use strict’;

// class Point {
// constructor(x, y) {
// this.x = x;
// this.y = y;
// }
// static distance(a, b) {
// const dx = a.x - b.x;
// const dy = a.y - b.y;
// return Math.sqrt(dx * dx + dy * dy);
// }
// }
// const p1 = new Point(5, 5);
// const p2 = new Point(10, 10);

// The correct way to call a static method


// console.log(Point.distance(p1, p2));

// Attempt to call a static method on an instance of the class


// try {
// console.log(p1.distance(p1, p2));
// }
// catch (exception) {
// console.log(exception.name + ‘: ’ + exception.message);
// }

/------------HOISTING---------------/
//salary();
//var amount=‘$30000’;
// function salary(){
// console.log(“My first salary: “, amount);
// var amount = ‘$50000’;
// console.log(“My second salary: “, amount);
// }

// var salary = function() {


// console.log(“My first salary: “, amount);
// var amount = ‘$50000’;
// console.log(“My second salary: “, amount);
// }
//salary();

/------------------Closures-----------------------/
// function currying(a) {
// return function(b) {
// return function(c) {
// return function(d) {
// return a+b+c+d;
// }
// }
// }
// }
// console.log(currying(1)(2)(3)(4));

// Memoization
// function sum() {
// const obj = {};
// return function(a,b){
// key=${a}${b};
// if(obj[key]) {
// console.log(“Not calculating”);
// return obj[key];
// } else {
// obj[key] = a+b;
// console.log(“Calculating”);
// return a+b;
// }
// }
// }

// Includes both case same order and rev order of parameter, it will not do the calculation
// function sum() {
// const obj = {};
// return function(a,b){
// key=${a}${b};
// keyR=${b}${a};
// if(obj[key] && obj[keyR]) {
// console.log(“Not calculating”);
// return obj[key];
// } else {
// obj[key] = a+b;
// obj[keyR] = a+b;
// console.log(“Calculating”);
// return a+b;
// }
// }
// }

// const s = sum();
// console.log(s(1,2));
// console.log(s(3,4));
// console.log(s(1,2));
// console.log(s(2,1));
// console.log(s(4,3));
// console.log(s(4,4));

/*--
Print from 10 to 1 without any loops only using setTimeout with 1 second delay each
--*/
// Recursive function
// function delay(count) {
// setTimeout(()=>{
// if(count>0) {
// console.log(count);
// count -= 1;
// delay(count);
// }
// return;
// },1000);
// }

// delay(10);
//delay(5);

/*-----
Print from 10 to 1 with for loop with 1 second delay each
-----*/
// function forLoopDelay(count) {
// let c=1;
// for(let i=count; i>=1; i--) {
// setTimeout(()=>{
// console.log(i)
// }, c*1000);
// c++;
// }
// }
//forLoopDelay(5);
//forLoopDelay(10);

// Without function only for loop


// let c=1;
// for(let i=10; i>=1; i--) {
// setTimeout(()=>{
// console.log(i)
// }, c*1000);
// c++;
// }

/*-----
Given an array of numbers ranging from -1000 to 1000 and array size can be in millions, find
first 3 numbers which will sum up to 0
-----*/

// function firstThree(arr) {
// const len = arr.length;
// const result = [];
// for (let i=0; i<3; i++){
// result.push(${arr[i]},${arr[len-i-1]});
// }
// return result.join(‘/’);
// }

//console.log(firstThree([-5,-4,-3,-2,-1,0,1,2,3,4,5]));

/*------
Given string A has length of million characters and string B has length of 256 and characters of
string B are non repetitive, find out if the substring B is present in any kind of order in string A,
but it has to be consecutive.
-------*/
// For eg:
// A = ‘awesomethingsarethereintheworld’ B = ‘lord’;
// At the end of the A string we can see ‘orld’ which can be a form of string B ‘lord
// function matchSubStr(strA, strB) {
// const len = strA.slice(0).length;
// let a = ‘’;
// let result = ‘’;
// for (let i=0; i<len; i++) {
// if(strB.includes(strA[i])) {
// a = a.concat(strA[i]);
// }
// }
// result = [...new Set(a.split(‘’).sort())].join(‘’);
// if (result === strB.split(‘’).sort().join(‘’)) {
// return ‘YES’
// }
// return ‘NO’;
// }
//console.log(matchSubStr(‘lloorrdd’, ‘lord’));
//console.log(matchSubStr(‘awesomethingsarethereintheworld’, ‘lord’));
//console.log(matchSubStr(‘abcdefgh’, ‘xyz’));
/*------
Finding factorial of a number
-------*/

// function factorial(n) {
// if(n==0) {
// return 1;
// }
// return n*factorial(n-1);
// }

//console.log(factorial(5));
//console.log(factorial(0));
//console.log(factorial(1));

/*-----
Fibonacci series (i.e. 0,1,1,2,3,5,8,13,21)
------*/

// function fibonacci(count) {
// let next = 1;
// let arr = [0,1];
// for(let i=2; i<count; i++){
// next = arr[i-2]+arr[i-1];
// arr.push(next);
// }
// console.log(arr.join(‘,’));
// }
// fibonacci(9);

You might also like