Number Length Sort[Edabit]

Edabit

Create a sorting function which sorts numbers not by numerical order, but by number length! This means sorting numbers with the least amount of digits first, up to the numbers with the most digits.

Examples

numberLenSort([1, 54, 1, 2, 463, 2]) ➞ [1, 1, 2, 2, 54, 463]

numberLenSort([999, 421, 22, 990, 32]) ➞ [22, 32, 999, 421, 990]

numberLenSort([9, 8, 7, 6, 5, 4, 31, 2, 1, 3]) ➞ [9, 8, 7, 6, 5, 4, 2, 1, 3, 31]

Notes

If two numbers have the same number of digits, return them in the order they first appeared (this makes it different to just sorting the numbers normally).SUGGEST EDITTestsConsole

  • Test Passed: Value == ‘[1, 1, 2, 2, 54, 463]’
  • Test Passed: Value == ‘[22, 32, 999, 421, 990]’
  • Test Passed: Value == ‘[9, 8, 7, 6, 5, 4, 2, 1, 3, 31]’
  • Test Passed: Value == ‘[94, 755, 1109, 9374, 3683, 8695, 4135, 5177, 3216]’
  • Test Passed: Value == ‘[73, 8013, 1753, 7283, 6830, 6278, 4931, 4556]’

Solution:

function numberLenSort(arr) {
  return arr.sort((a, b) => a.toString().length - b.toString().length);
}

Recursion: Find the Longest Word [Edabit]

Edabit

Write a recursive function that will return the longest word in a sentence. In cases where more than one word is found, return the first one.

Examples

findLongest("A thing of beauty is a joy forever.") ➞ "forever"

findLongest("Forgetfulness is by all means powerless!") ➞ "forgetfulness"

findLongest("Strengths is the longest and most commonly used word that contains only a single vowel.") ➞ "strengths"

Notes

  • Special characters and symbols don’t count as part of the word.
  • Return the longest word found in lowercase letters.
  • You are expected to solve this challenge via a recursive approach.
  • A non-recursive version of this challenge can be found in here.
  • If you think recursion is fun, a collection of challenges can be found in here.

Solution:

function findLongest(sentence) {
  /* your recursive solution here.
    but i am ishtoopid when it 
    comes to recursion, but I can do 
    jugaad 😛
  */
  return sentence.split(" ").length === 1
    ? sentence
    : findLongest(
        sentence
          .toLowerCase()
          .replace(/[^a-z ]/gi, " ")
          .split(" ")
          .sort((a, b) => b.length - a.length)[0]
      );
}

Lychrel Numbers[Edabit]

Edabit

The following is the Lychrel test.

Start with any positive number. Add the number with the number formed by reversing its digits. Is the sum a palindrome? If not, repeat the process.

For most numbers, a palindrome is produced after a few iterations (7 or fewer) of the process above. Numbers that never reach a palindrome are called Lychrel numbers. No number in base 10 has been proven to be a Lychrel number, but numbers that don’t produce palindromes after an unusually high number of iterations of the reverse-and-add process are said to be Lychrel candidates

Create a function that takes a number and returns true if it is a Lychrel candidate. If it isn’t, return the number of reverse-and-add iterations it takes to produce a palindrome. For this challenge, the threshold for a Lychrel candidate is >=500 iterations.

Examples

lychrel(33) ➞ 0
// Already a palindrome.

lychrel(65) ➞ 1
// 65+56 -> 121

lychrel(348) ➞ 3
// 348+843 -> 1191+1911 -> 3102+2013 -> 5115

lychrel(295) ➞ true

Solution:

function lychrel(n) {
  let count = 0;
  while (n.toString() !== [...n.toString()].reverse().join("")) {
    n += parseInt([...n.toString()].reverse().join(""));
    count++;
    if (count > 25) return true;
  }
  return count;
}

Left Shift by Powers of Two[Edabit]

Edabit

The left shift operation is similar to multiplication by powers of two.

Sample calculation using the left shift operator (<<):

10 << 3 = 10 * 2^3 = 10 * 8 = 80
-32 << 2 = -32 * 2^2 = -32 * 4 = -128
5 << 2 = 5 * 2^2 = 5 * 4 = 20

Write a function that mimics (without the use of <<) the left shift operator and returns the result from the two given integers.

Examples

shiftToLeft(5, 2) ➞ 20

shiftToLeft(10, 3) ➞ 80

shiftToLeft(-32, 2) ➞ -128

shiftToLeft(-6, 5) ➞ -192

shiftToLeft(12, 4) ➞ 192

shiftToLeft(46, 6) ➞ 2944

Notes

  • There will be no negative values for the second parameter y.
  • This challenge is more like recreating of the left shift operation, thus, the use of the operator directly is prohibited.
  • Optionally, you can solve this challenge via recursion.
  • A recursive version of this challenge can be found here.

Solution:

function shiftToLeft(x, y) {
  let zero = "";
  while (y--) {
    zero += "0";
  }
  zero = x.toString(2) + zero;
  console.log(zero);
  return parseInt(zero, 2);
}

1051. Height Checker [Leetcode]

Students are asked to stand in non-decreasing order of heights for an annual photo.

Return the minimum number of students that must move in order for all students to be standing in non-decreasing order of height.

Notice that when a group of students is selected they can reorder in any possible way between themselves and the non selected students remain on their seats.

Example 1:

Input: heights = [1,1,4,2,1,3]
Output: 3
Explanation: 
Current array : [1,1,4,2,1,3]
Target array  : [1,1,1,2,3,4]
On index 2 (0-based) we have 4 vs 1 so we have to move this student.
On index 4 (0-based) we have 1 vs 3 so we have to move this student.
On index 5 (0-based) we have 3 vs 4 so we have to move this student.

Example 2:

Input: heights = [5,1,2,3,4]
Output: 5

Example 3:

Input: heights = [1,2,3,4,5]
Output: 0

Constraints:

  • 1 <= heights.length <= 100
  • 1 <= heights[i] <= 100

Solution:

/**
 * url: https://leetcode.com/problems/height-checker/
 * github: theketan2
 * @param {number[]} heights
 * @return {number}
 */
var heightChecker = function (heights) {
  let temp = [].concat(heights);
  heights.sort((a, b) => parseInt(a) - parseInt(b));
  console.log(heights);
  let sol = 0;
  for (let i in temp) {
    console.log(heights[i], " == ", temp[i]);
    if (temp[i] !== heights[i]) sol++;
  }
  return sol;
};

Headline Hash Tags[Edabit]

Write a function that retrieves the top 3 longest words of a newspaper headline and transforms them into hashtags. If multiple words tie for the same length, retrieve the word that occurs first.

Examples

getHashTags("How the Avocado Became the Fruit of the Global Trade")
➞ ["#avocado", "#became", "#global"]

getHashTags("Why You Will Probably Pay More for Your Christmas Tree This Year")
➞ ["#christmas", "#probably", "#will"]

getHashTags("Hey Parents, Surprise, Fruit Juice Is Not Fruit")
➞ ["#surprise", "#parents", "#fruit"]

getHashTags("Visualizing Science")
➞ ["#visualizing", "#science"]

Notes

  • If the title is less than 3 words, just order the words in the title by length in descending order (see example #4).
  • Punctuation does not count towards a word’s length.

Solution:

function getHashTags(str) {
  let strArr = str
    .toLowerCase()
    .replace(/[^a-z ]/gi, "")
    .split(" ")
    .sort((a, b) => b.length - a.length)
    .map((word) => "#" + word);
  return strArr.splice(0, 3);
}

Remove the Letters ABC[Edabit]

Edabit

Create a function that will remove the letters “a”, “b” and “c” from the given string and return the modified version. If the given string does not contain “a”, “b”, or “c”, return null.

Examples

removeABC("This might be a bit hard") ➞ "This might e  it hrd"

removeABC("hello world!") ➞ null

removeABC("") ➞ null

Notes

If the given string does not contain “a”, “b”, or “c”, return null.

Solution:

function removeABC(str) {
		let newStr = str.replace(/[abc]/gi,"");
		return newStr === str? null: newStr;
}

RGB to Hex Color Converter [Edabit]

Create a function that converts color in RGB format to Hex format.

Examples

rgbToHex("rgb(0, 128, 192)") ➞ "#0080c0"

rgbToHex("rgb(45, 255, 192)") ➞ "#2dffc0"

rgbToHex("rgb(0, 0, 0)") ➞ "#000000"

Notes

The Hex format should be displayed in lowercase.

Solution:

function rgbToHex(col) {
  let numArr = col.replace(/[^0-9 ]/g, "").split(" ");
  return (
    "#" +
    numArr
      .map((num) =>
        num === "0"
          ? "00"
          : Number(num).toString(16).length === 1
          ? "0" +""+ Number(num).toString(16)
          : Number(num).toString(16)
      )
      .join("")
  );
}

917. Reverse Only Letters [Leetcode]

Leetcode

Given a string S, return the “reversed” string where all characters that are not a letter stay in the same place, and all letters reverse their positions.

Example 1:

Input: "ab-cd"
Output: "dc-ba"

Example 2:

Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"

Example 3:

Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"

Note:

  1. S.length <= 100
  2. 33 <= S[i].ASCIIcode <= 122 
  3. S doesn’t contain \ or "

Solution:

/**
 * url : https://leetcode.com/problems/reverse-only-letters
 * Github: theketan2
 * @param {string} S
 * @return {string}
 */
var reverseOnlyLetters = function (S) {
  let arr = S.replace(/[^a-zA-Z]/g, "").split("");
  let sol = "";
  console.log(arr);
  for (let ch of [...S]) {
    if ((ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z")) {
      sol += arr.pop();
    } else {
      sol += ch;
    }
  }
  return sol;
};

1403. Minimum Subsequence in Non-Increasing Order [Leetcode]

Given the array nums, obtain a subsequence of the array whose sum of elements is strictly greater than the sum of the non included elements in such subsequence. 

If there are multiple solutions, return the subsequence with minimum size and if there still exist multiple solutions, return the subsequence with the maximum total sum of all its elements. A subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. 

Note that the solution with the given constraints is guaranteed to be unique. Also return the answer sorted in non-increasing order.

Example 1:

Input: nums = [4,3,10,9,8]
Output: [10,9] 
Explanation: The subsequences [10,9] and [10,8] are minimal such that the sum of their elements is strictly greater than the sum of elements not included, however, the subsequence [10,9] has the maximum total sum of its elements. 

Example 2:

Input: nums = [4,4,7,6,7]
Output: [7,7,6] 
Explanation: The subsequence [7,7] has the sum of its elements equal to 14 which is not strictly greater than the sum of elements not included (14 = 4 + 4 + 6). Therefore, the subsequence [7,6,7] is the minimal satisfying the conditions. Note the subsequence has to returned in non-decreasing order.  

Example 3:

Input: nums = [6]
Output: [6]

Constraints:

  • 1 <= nums.length <= 500
  • 1 <= nums[i] <= 100

Solution:

/**
 * url: https://leetcode.com/problems/minimum-subsequence-in-non-increasing-order/submissions/
 * github: theketan2
 * @param {number[]} nums
 * @return {number[]}
 */
var minSubsequence = function (nums) {
  nums.sort((a, b) => parseInt(b) - parseInt(a));
  let sum = nums.reduce((acc, curr) => acc + curr);
  for (let i = 1; i < nums.length; i++) {
    let subSum = nums.slice(0, i).reduce((acc, curr) => acc + curr);
    if (subSum > sum - subSum) {
      return nums.splice(0, i);
    }
  }
  return nums;
};