Advertisement
samimwebdev

DSA fundamentals problem solving-1

Nov 28th, 2023 (edited)
606
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Write a function called getSum that takes in two numbers and returns the sum of those two numbers
  2. function getSum(num1, num2) {
  3.   return num1 + num2
  4.   //write function
  5. }
  6.  
  7. // console.log(getSum(1, 2)) // 3
  8. // getSum(10, 5) // 15
  9. // getSum(2, 2) // 4
  10. // getSum(10, 5) // 15
  11.  
  12. //=================================================
  13.  
  14. // Write a function called calculator that takes in 2 numbers and an operator and returns the result of the calculation.
  15. function calculator(num1, num2, operator) {
  16.   //   let result
  17.   //   switch (operator) {
  18.   //     case '+':
  19.   //       result = num1 + num2
  20.   //       break
  21.   //     case '-':
  22.   //       result = num1 - num2
  23.   //       break
  24.   //     case '*':
  25.   //       result = num1 * num2
  26.   //       break
  27.   //     case '/':
  28.   //       result = num1 / num2
  29.   //       break
  30.   //     default:
  31.   //       throw new Error('Not a valid Operator')
  32.   //   }
  33.  
  34.   if (operator === '+') {
  35.     return num1 + num2
  36.   }
  37.   if (operator === '-') return num1 - num2
  38.   if (operator === '*') return num1 * num2
  39.   if (operator === '/') return num1 / num2
  40.   throw new Error('Not a valid Operator')
  41.  
  42.   //   return result
  43. }
  44.  
  45. console.log(calculator(1, 2, '*')) // 3
  46. // calculator(10, 5, '-') // 5
  47. // calculator(2, 2, '*') // 4
  48. // calculator(10, 5, '/') // 2
  49.  
  50. //=================================================
  51.  
  52. // Write a function called countOccurrences that takes in a string and a character and returns the number of occurrences of that character in the string.
  53. // Lowercase and uppercase characters are considered different characters
  54. function countOccurrences(str, char) {
  55.   //write code here
  56.   let count = 0
  57.   for (let letter of str) {
  58.     letter === char && count++
  59.   }
  60.   return count
  61. }
  62.  
  63. console.log(countOccurrences('hello', 'l')) //2
  64. // countOccurrences('hello', 'z') // 0
  65.  
  66. // You may assume that each word consists of only letters and spaces
  67. function titleCase(str) {
  68.   //write code here
  69.   //make all sentence lowecase
  70.   //   const lowecaseStr = str.toLowerCase()
  71.   //   console.log(lowecaseStr)
  72.  
  73.   //   //devide by space (split)
  74.   //   const splitStr = lowecaseStr.split(' ')
  75.   //   console.log(splitStr)
  76.   //   //make each array elements first letter to uppercase
  77.   //   for (let i = 0; i < splitStr.length; i++) {
  78.   //     splitStr[i] = splitStr[i][0].toUpperCase() + splitStr[i].slice(1)
  79.   //   }
  80.   //   console.log(splitStr)
  81.   //  return splitStr.join(' ')
  82.   return str.replace(/\b\w/g, (match) => match.toUpperCase())
  83. }
  84.  
  85. console.log(titleCase("I'm a little tea pot")) // I'm A Little Tea Pot
  86. // titleCase('sHoRt AnD sToUt'); // Short And Stout
  87. // titleCase('HERE IS MY HANDLE HERE IS MY SPOUT'); // Here Is My Handle Here Is My Spout
  88.  
  89. //=================================================
  90.  
  91. // Write a function called removeDuplicates that takes in an array and returns a new array with duplicates removed.
  92. // function removeDuplicates(arr) {
  93. // const resultSet = new Set(arr)
  94. // console.log(Array.from(resultSet))
  95. // return Array.from(resultSet)
  96.  
  97. //   const resultArr = []
  98.  
  99. //   for (let num of arr) {
  100. //     if (!resultArr.includes(num)) {
  101. //       resultArr.push(num)
  102. //     }
  103. //   }
  104.  
  105. //   console.log(resultArr)
  106. // }
  107.  
  108. // removeDuplicates([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  109. // removeDuplicates([1, 1, 1, 1, 1, 1, 1, 1, 1, 1]) // [1]
  110. // removeDuplicates([1, 2, 3, 4, 5, true, 1, 'hello' 2, 3, 'hello', true]); // [1, 2, 3, 4, 5, true, 'hello']
  111.  
  112. //=================================================
  113.  
  114. // Write a function called arrayIntersection that takes in two arrays and returns an array containing the intersection of the two input arrays (i.e., the common elements that appear in both arrays).
  115.  
  116. function arrayIntersection(arr1, arr2) {
  117.   //   const resultArr = []
  118.  
  119.   //   for (let num of arr1) {
  120.   //     console.log(num)
  121.   //     if (arr2.includes(num)) {
  122.   //       resultArr.push(num)
  123.   //     }
  124.   //   }
  125.  
  126.   //   console.log(Array.from(new Set(resultArr)))
  127.   const set1 = new Set(arr1)
  128.   const intersectionArr = []
  129.  
  130.   for (let num of arr2) {
  131.     console.log(num)
  132.     if (set1.has(num)) {
  133.       intersectionArr.push(num)
  134.     }
  135.   }
  136.   return intersectionArr
  137. }
  138.  
  139. console.log(arrayIntersection([1, 2, 3, 3, 4, 5], [1, 3, 5, 7, 9])) // should return [1, 3, 5]
  140. // arrayIntersection([1, 1, 1, 1, 1], [2, 2, 2, 2, 2]); // should return []
  141. // arrayIntersection([1, 2, 3, 4, 5], [5, 4, 3, 2, 1]); // should return [1, 2, 3, 4, 5]
  142.  
  143. //=================================================
  144.  
  145. // Write a function called displayLikes that takes in an array of names and returns a string of who likes the post.
  146.  
  147. // The function should return a string formatted as follows:
  148.  
  149. // If no one likes it, it should return 'no one likes this'
  150. // If one person likes it, it should return '{name} likes this'
  151. // If two people like it, it should return '{name1} and {name2} like this'
  152. // If three people like it, it should return '{name1}, {name2} and {name3} like this'
  153. // If more than three people like it, it should return '{name1}, {name2} and {x} others like this'
  154.  
  155. function displayLikes(namesArr) {
  156.   // Get the length of the array
  157.   const length = namesArr.length
  158.  
  159.   // Return the appropriate string based on the length of the array
  160.   if (length === 0) {
  161.     return 'no one likes this'
  162.   } else if (length === 1) {
  163.     return `${namesArr[0]} likes this`
  164.   } else if (length === 2) {
  165.     return `${namesArr[0]} and ${namesArr[1]} like this`
  166.   } else if (length === 3) {
  167.     return `${namesArr[0]}, ${namesArr[1]} and ${namesArr[2]} like this`
  168.   } else {
  169.     return `${namesArr[0]}, ${namesArr[1]} and ${length - 2} others like this`
  170.   }
  171. }
  172.  
  173. // displayLikes([]) // 'no one likes this'
  174. // displayLikes(['Peter']) // 'Peter likes this'
  175. // displayLikes(['Jacob', 'Alex']) // 'Jacob and Alex like this'
  176. // displayLikes(['Max', 'John', 'Mark']) // 'Max, John and Mark like this'
  177. console.log(displayLikes(['Alex', 'Jacob', 'Mark', 'Max'])) // 'Alex, Jacob and 2 others like this'
  178. // displayLikes(['Alex', 'Jacob', 'Mark', 'Max', 'Jill']) // 'Alex, Jacob and 3 others like this'
  179.  
  180. //=================================================
  181. // Write a function called findMissingNumber that takes in an array of unique numbers from 1 to n (inclusive), where one number is missing. It should return the missing number.
  182.  
  183. // If an empty array is passed in, it should return 1
  184. // If nothing is passed in, it should return undefined
  185.  
  186. function findMissingNumber(arr) {
  187.   //write code here
  188.   if (!arr || !Array.isArray(arr)) return undefined
  189.   if (arr.length === 0) return 1
  190.  
  191.   const n = arr.length + 1
  192.  
  193.   const expectedSum = (n * (n + 1)) / 2
  194.   console.log(expectedSum)
  195.  
  196.   //   let total = 0
  197.   //   for(let num of arr){
  198.   //     total += num
  199.   //   }
  200.   //   console.log(total)
  201.   const totalSum = arr.reduce((total, num) => total + num, 0)
  202.  
  203.   console.log(expectedSum - totalSum)
  204.   return expectedSum - totalSum
  205.   //(n * (n +1)) / 2
  206. }
  207.  
  208. console.log(findMissingNumber([1, 2, 3, 4, 6, 7, 8, 9, 10])) // 5
  209. // findMissingNumber([10, 8, 6, 7, 5, 4, 2, 3, 1]); // 9
  210. // findMissingNumber([10, 5, 1, 2, 4, 6, 8, 3, 9]); // 7
  211.  
  212. //=================================================
  213.  
  214. // Write a function called findMissingLetter that takes in an array of consecutive (increasing) letters as input and returns the missing letter in the array.
  215.  
  216. function findMissingLetter(arr) {
  217.   const alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
  218.   const startIndex = alphabet.indexOf(arr[0])
  219.  
  220.   for (let i = 0; i < arr.length; i++) {
  221.     if (arr[i] !== alphabet[startIndex + i]) {
  222.       return alphabet[startIndex + i]
  223.     }
  224.   }
  225.  
  226.   //write code here
  227. }
  228.  
  229. console.log(findMissingLetter(['a', 'b', 'c', 'd', 'f'])) // => "e"
  230. // findMissingLetter(['O', 'Q', 'R', 'S']); // => "P"
  231. // findMissingLetter(['t', 'u', 'v', 'w', 'x', 'z']); // => "y"
  232.  
  233. //=================================================
  234.  
  235. // Write a function called validateEmail that takes in a string and returns whether the string is a valid email address. For the purposes of this challenge, a valid email address is defined as a string that contains an @ symbol and a . symbol.
  236.  
  237. function validateEmail(email) {
  238.   //   const emailRegex = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/
  239.   //   return emailRegex.test(email)
  240.   // Check if the email contains the "@" symbol
  241.   //   if (email.indexOf('@') === -1) {
  242.   //     return false
  243.   //   }
  244.   //   // Split the email into the local part and domain
  245.   //   const [localPart, domain] = email.split('@')
  246.   //   // Check if the local part and domain meet the minimum length requirements
  247.   //   if (localPart.length === 0 || domain.length < 3) {
  248.   //     return false
  249.   //   }
  250.   //   // Check if the domain extension consists of at least two characters
  251.   //   const domainExtension = domain.split('.')
  252.   //   if (domainExtension.length < 2 || domainExtension[1].length < 2) {
  253.   //     return false
  254.   //   }
  255.   //   // If all checks pass, return true
  256.   //   return true
  257.   //write code here
  258. }
  259.  
  260. console.log(validateEmail('john@gmail.com')) // true
  261. validateEmail('john@gmail') // false
  262.  
  263. //=================================================
  264.  
  265. // Write a function called diceGameSimulation that simulates this dice game. The function should take one argument:
  266.  
  267. // numSimulations: The number of times to simulate the dice game.
  268. // The game rules are if a 7 or 11 are rolled, the player wins and they get a result of win. If a 2, 3 or 12 are rolled they lose and get a result of lose. Anything else and they get a result of roll again.
  269.  
  270. // The function should return an array of objects, where each object represents a simulation result. Each object should contain the following properties:
  271.  
  272. // dice1: The value of the first dice (a random number between 1 and 6).
  273. // dice2: The value of the second dice (a random number between 1 and 6).
  274. // sum: The sum of the two dice values.
  275. // result: The result of the roll, which can be "win", "lose", or "roll again".
  276.  
  277. function rollDice() {
  278.   return Math.floor(Math.random() * 6 + 1)
  279. }
  280. function diceGameSimulation(numOfTry) {
  281.   const results = []
  282.   //write code here
  283.   for (let i = 0; i < numOfTry; i++) {
  284.     const dice1 = rollDice()
  285.     const dice2 = rollDice()
  286.     const sum = dice1 + dice2
  287.     let result = ''
  288.     if (sum === 7 || sum === 11) {
  289.       result = 'win'
  290.     } else if (sum === 2 || sum === 3 || sum === 12) {
  291.       result = 'lose'
  292.     } else {
  293.       result = 'Roll Again'
  294.     }
  295.     results.push({ dice1, dice2, sum, result })
  296.   }
  297.  
  298.   console.log(results)
  299. }
  300.  
  301. diceGameSimulation(10)
  302.  
  303. /*
  304.   { dice1: 1, dice2: 5, sum: 6, result: 'roll again' },
  305.   { dice1: 5, dice2: 6, sum: 11, result: 'win' },
  306.   { dice1: 1, dice2: 1, sum: 2, result: 'lose' }
  307. */
  308.  
  309. // Write a function called formatPhoneNumber that takes in an array of numbers and returns a string representing the phone number formed by concatenating the numbers in the specified format.
  310.  
  311. //=================================================
  312.  
  313. function formatPhoneNumber(numbers) {
  314.   //write code here
  315.   // Get the first 3 numbers and join them together
  316.   const areaCode = numbers.slice(0, 3).join('')
  317.   // Get the next 3 numbers and join them together
  318.   const prefix = numbers.slice(3, 6).join('')
  319.   // Get the last 4 numbers and join them together
  320.   const lineNumber = numbers.slice(6).join('')
  321.   console.log(`(${areaCode}) ${prefix}-${lineNumber}`)
  322.   return `(${areaCode}) ${prefix}-${lineNumber}`
  323.  
  324. }
  325.  
  326. formatPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0]); // => "(123) 456-7890"
  327. // formatPhoneNumber([5, 1, 9, 5, 5, 5, 4, 4, 6, 8]); // => "(519) 555-4468"
  328. // formatPhoneNumber([3, 4, 5, 5, 0, 1, 2, 5, 2, 7]); // => "(345) 501-2527"
  329.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement