Posts

Showing posts from March, 2024

Today I have solved the problem in javascript

 Consider the following scenario: there are N mice and N holes placed at integer points along a line. Given this, find a method that maps mice to holes such that the largest number of steps any mouse takes is minimized.Each move consists of moving one mouse one unit to the left or right, and only one mouse can fit inside each hole.For example, suppose the mice are positioned at [1, 4, 9, 15], and the holes are located at [10, -5, 0, 16]. In this case, the best pairing would require us to send the mouse at 1 to the hole at -5, so our function should return 6. const mice = [1, 4, 9, 15]; const holes = [10, -5, 0, 16]; function minSteps(mice, holes) {    mice.sort((a, b) => a - b);     holes.sort((a, b) => a - b); let maxSteps = 0;     for (let i = 0; i < mice.length; i++) {         let steps = Math.abs(mice[i] - holes[i]);         if (steps > maxSteps) {             maxStep...

Today I have solved the problem in javascript

 The United States uses the imperial system of weights and measures, which means that there are many different, seemingly arbitrary units to measure distance. There are 12 inches in a foot, 3 feet in a yard, 22 yards in a chain, and so on. Create a data structure that can efficiently convert a certain quantity of one unit to the correct amount of any other unit. You should also allow for additional units to be added to the system. function convert(quantity, fromUnit, toUnit) {   if (!conversions[fromUnit] || !conversions[toUnit]) {     return "Invalid units";   }   return quantity * conversions[fromUnit][toUnit]; } const conversions = {   inch: {     foot: 1 / 12,     yard: 1 / 36,     mile: 1 / 63360,        },   foot: {     inch: 12,     yard: 1 / 3,     mile: 1 / 5280,        },   yard: {     inch: 36,     foot: 3,  ...

Today I have solved the problem in javascript

In chess, the Elo rating system is used to calculate player strengths based on game results. A simplified description of the Elo system is as follows. Every player begins at the same score. For each subsequent game, the loser transfers some points to the winner, where the amount of points transferred depends on how unlikely the win is. For example, a 1200-ranked player should gain much more points for beating a 2000-ranked player than for beating a 1300-ranked player.Implement this system. var playerA = 1200; var playerB = 2000; var result = 1;  var kFactor = 32;  var newRatings = updateRating(playerA, playerB, result, kFactor); function expectedScore(ratingA, ratingB) {     return 1 / (1 + Math.pow(10, (ratingB - ratingA) / 400)); } function updateRating(ratingA, ratingB, result, kFactor) {     var expectedScoreA = expectedScore(ratingA, ratingB);     var expectedScoreB = expectedScore(ratingB, ratingA);     var newRatingA = ratingA + k...

Today I have solved the problem in javascript

 In chess, the Elo rating system is used to calculate player strengths based on game results. A simplified description of the Elo system is as follows. Every player begins at the same score. For each subsequent game, the loser transfers some points to the winner, where the amount of points transferred depends on how unlikely the win is. For example, a 1200-ranked player should gain much more points for beating a 2000-ranked player than for beating a 1300-ranked player. Implement this system. const initialRating = 1000; const players = {     "Alice": initialRating,     "Bob": initialRating,     "Charlie": initialRating }; const winner = "Alice"; const loser = "Bob"; const { winnerNewRating, loserNewRating } = updateRatings(players[winner], players[loser]); players[winner] = winnerNewRating; players[loser] = loserNewRating; function expectedScore(playerRating, opponentRating) {     return 1 / (1 + Math.pow(10, (opponentRating - playerRati...

Today I have solved the problem in javascript

 A Boolean formula can be said to be satisfiable if there is a way to assign truth values to each variable such that the entire formula evaluates to true. For example, suppose we have the following formula, where the symbol ¬ is used to denote negation:(¬c OR b) AND (b OR c) AND (¬b OR c) AND (¬c OR ¬a)One way to satisfy this formula would be to let a = False, b = True, and c = True. This type of formula, with AND statements joining tuples containing exactly one OR, is known as 2-CNF.Given a 2-CNF formula, find a way to assign truth values to satisfy it, or return False if this is impossible. const formula = [     ['¬c', 'b'],     ['b', 'c'],     ['¬b', 'c'],     ['¬c', '¬a'] ]; function satisfy2CNF(formula) {     const assignament = {};          for (const [a, b] of formula) {         if ((a in assignment && assignment[a] !== b) || (b in assignment && assignment[b] !== a)...

Today I have learned basics in python

  B asics in python What is Python basics? Python Basics is for people who want to learn Python programming—whether you are a complete beginner to programming, or a developer with experience in another language. What Are Python Raw Strings? What's the Zen of Python? Begin your Python journey with these beginner-friendly tutorials. Learn fundamental Python concepts to kickstart your career. What should I learn in Python? Fundamentals Syntax – introduce you to the basic Python programming syntax. Variables – explain to you what variables are and how to create concise and meaningful variables. Strings – learn about string data and some basic string operations. Numbers – introduce to you the commonly-used number types including integers and floating-point numbers. a= 45 b= 60 c= 70 d= "My age {1}.{1} is {0} " print(d.format(a,b,c)) Output: my age 60.60 is 45 try:   print("hiii") except:   print("error") else:   print("good morning") Output: hiii ...

Today I have solved problem in javascript

 Given integers M and N, write a program that counts how many positive integer pairs (a, b) satisfy the following conditions: a + b = M a XOR b = N const M = 10; const N = 5; function countIntegerPairs(M, N) {     let count = 0;     for (let a = 0; a <= M; a++) {         let b = M - a;         if ((a ^ b) === N) {             count++;         }     }     return count; } console.log(countIntegerPairs(M, N));  Output: 0

Today I have learned Iteration in python

 Iteration in python: Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__ () and __next__ (). Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from. All these objects have a iter () method which is used to get an iterator: When it comes to iteration in Python, you’ll often hear people talking about iterable objects or just iterables. As the name suggests, an iterable is an object that you can iterate over. To perform this iteration, you’ll typically use a for loop. Pure iterable objects typically hold the data themselves. a= ("apple","banana","orange") b= iter(a) print(next(b)) print(next(b)) print(next(b)) Output: apple banana orange import datetime x=datetime.datetime(2024,3,10) print(x.strftime("%A")) Output: Sunday

Today I have solved the problem in javascript

 The 24 game is played as follows. You are given a list of four integers, each between 1 and 9, in a fixed order. By placing the operators +, -, *, and / between the numbers, and grouping them with parentheses, determine whether it is possible to reach the value 24. For example, given the input [5, 2, 7, 8], you should return True, since (5 * 2 - 7) * 8 = 24. Write a function that plays the 24 game. const nums = [5, 2, 7, 8]; function judgePoint24(nums) {   const EPSILON = 1e-6;   const TARGET = 24;   const dfs = (arr) => {     if (arr.length === 1) {       return Math.abs(arr[0] - TARGET) < EPSILON;     }     for (let i = 0; i < arr.length; i++) {       for (let j = 0; j < arr.length; j++) {         if (i !== j) {           const next = [];           for (let k = 0; k < arr.length; k++) {           ...

Today I have solved the problem in javascript

 PageRank is an algorithm used by Google to rank the importance of different websites. While there have been changes over the years, the central idea is to assign each site a score based on the importance of other pages that link to that page. More mathematically, suppose there are N sites, and each site i has a certain count Ci of outgoing links. Then the score for a particular site Sj is defined as : score(Sj) = (1 - d) / N + d * (score(Sx) / Cx+ score(Sy) / Cy+ ... + score(Sz) / Cz)) Here, Sx, Sy, ..., Sz denote the scores of all the other sites that have outgoing links to Sj, and d is a damping factor, usually set to around 0.85, used to model the probability that a user will stop searching. Given a directed graph of links between various websites, write a program that calculates each site's page rank. const graph = {   'A': ['B', 'C'],   'B': ['A'],   'C': ['A', 'B'] }; const result = calculatePageRank(graph); fun...

Today I have learned for and if loop in Python

  What is an IF statement in a for loop? As you can see, an if statement within a for loop is perfect to evaluate a list of numbers in a range (or elements in a list) and put them into different buckets, tag them, or apply functions on them – or just simply print them. What is the difference between if and for loop in Python? For loops complete an iterative action for a defined number of elements, while if statements test a condition and then complete an action. Here’s how to combine them. Control flow structures like if statements and for loops are powerful ways to create logical, clean and well organized code in Python. fruit=["apple","grape","banana","kiwi"], veg=["cabbage","tomato"] for x in fruit:  for y in veg:   print(x,y) Output: ['apple', 'grape', 'banana', 'kiwi'] cabbage ['apple', 'grape', 'banana', 'kiwi'] tomato a="apple" b="orange...

Today I have solved the problem in javascript

 Given an integer n, find the next biggest integer with the same number of 1-bits on. For example, given the number 6 (0110 in binary), return 9 (1001). const inputNumber = 6; const result = nextIntegerWithSameBits(inputNumber); function nextIntegerWithSameBits(n) {    const countBits = (num) => num.toString(2).split('1').length - 1;  const originalBits = countBits(n);  let nextInteger = n + 1;     while (countBits(nextInteger) !== originalBits) {         nextInteger++;     }  return nextInteger; } console.log(result);   Output: 9

Today I have solved the problem in javascript

 Given a linked list, uniformly shuffle the nodes. What if we want to prioritize space over time? const list = ListNode(1, ListNode(2, ListNode(3, ListNode(4, ListNode(5))))); const shuffledList = shuffleLinkedList(list); function ListNode(value, next = null) {   return { value, next }; } function shuffleLinkedList(head) {      let current = head;   let count = 0;   while (current) {     count++;     current = current.next;   } current = head; for (let i = count - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1));  let nodeI = head;     for (let k = 0; k < i; k++) {       nodeI = nodeI.next;     } let nodeJ = head;     for (let k = 0; k < j; k++) {       nodeJ = nodeJ.next;     } const temp = nodeI.value;     nodeI.value = nodeJ.value;     nodeJ.value = temp; current = current.next;   } return head; } consol...

Today I have learned basic in Python

  What is Python basics? Python Basics is for people who want to learn Python programming—whether you are a complete beginner to programming, or a developer with experience in another language. What Are Python Raw Strings? What's the Zen of Python? Begin your Python journey with these beginner-friendly tutorials. Learn fundamental Python concepts to kickstart your career. How to learn Python? Write a lot of Python code - The only way you can learn programming is by writing a lot of code. Python is a powerful general-purpose programming language. Our Python tutorial will guide you to learn Python one step at a time with the help of examples. Is Python a good language for beginners? Python is a popular general-purpose programming language. It is used in machine learning, web development, desktop applications, and many other fields. Fortunately for beginners, Python has a simple, easy-to-use syntax. This makes Python a great language to learn for beginners. Our Python t...

Today I have solved the problem in javascript

 Write a program to determine how many distinct ways there are to create a max heap from a list of N given integers. For example, if N = 3, and our integers are [1, 2, 3], there are two ways, shown below.   3      3  / \    / \ 1   2  2   1 const N = 3; const result = countMaxHeapWays(N); function nCr(n, r) {     if (r === 0 || n === r) return 1;     return nCr(n - 1, r - 1) + nCr(n - 1, r); } function leftChild(index) {     return 2 * index + 1; } function calculateWays(n, dp) {     if (n <= 1) {         return 1;     }     if (dp[n] !== undefined) {         return dp[n];     }     let leftSubtreeSize = 0;     const height = Math.floor(Math.log2(n));     const lastLevelNodes = n - Math.pow(2, height) + 1;     if (lastLevelNodes >= Math.pow(2, height - 1)) {   ...

Today I have learned basic in python

  List Lists are used to store multiple items in a single variable. Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are  Tuple ,  Set , and  Dictionary , all with different qualities and usage. List Items List items are ordered, changeable, and allow duplicate values. List items are indexed, the first item has index  [0] , the second item has index  [1]  etc. Ordered When we say that lists are ordered, it means that the items have a defined order, and that order will not change. If you add new items to a list, the new items will be placed at the end of the list. listnew=["apple","banana","grapes"] listnew.append("orange") listnew.insert(1,"kiwi") new1=["mango","cherry"] listnew.extend(new1) listnew.remove("apple") listnew.pop(2) del listnew[1] print(listnew) Output: ['kiwi', 'orange', 'mango', 'cherry'] How to add elements in a ...