Journal Archive

function scramble(str1, str2) {
 // simple case 
  const length1 = str1.length;
  const length2 = str2.length;
  if (length1 < length2) return false;
  
  const str2Letters = str2.split("");
  const str1Letters = str1.split("");
  
  function groupAlphabets(arr) {
    let alphabetGrouping = {}
    arr.forEach( letter => {
      if (alphabetGrouping[letter]) {
        alphabetGrouping[letter] += 1;
      } else {
        alphabetGrouping[letter] = 1;
      }
    });
    return alphabetGrouping;
  }
  
  let str1Grouping = groupAlphabets(str1Letters);
  let str2Grouping = groupAlphabets(str2Letters);
  
  for (let letter in str2Grouping) {
    if (!str1Grouping[letter] || str1Grouping[letter] < str2Grouping[letter]) return false;
  }
  return true;
}

Day 7: Solving one of the Kata on CodeWars

Scramblies 5 kyu

Complete the function scramble(str1, str2) that returns true if a portion of str1 characters can be rearranged to match str2, otherwise returns false.

Notes:
Only lower case letters will be used (a-z). No punctuation or digits will be included. Performance needs to be considered.

Examples

scramble('rkqodlw', 'world') ==> True scramble('cedewaraaossoqqyt', 'codewars') ==> True scramble('katas', 'steak') ==> False