Skip to content Skip to sidebar Skip to footer

How To Write A Function That Returns True If A Portion Of Str1 Can Be Rearranged To Str2?

I am having trouble with below question. I basically have to write a code/function that returns true if a portion of str1 can be rearraged to str2. Write function scramble(str1,str

Solution 1:

You could use a hash table with the count of the letters and check with count and decrement the count.

This proposal does not mutate the arrays.

function scramble(str1, str2) {
    var count = Object.create(null);

    Array.prototype.forEach.call(str1, function(a) {
        count[a] = (count[a] || 0) + 1;
    });

    return Array.prototype.every.call(str2, function(a) {
        return count[a]--;
    });
}

console.log(scramble('rkqodlw', 'world'));              // true
console.log(scramble('cedewaraaossoqqyt', 'codewars')); // true
console.log(scramble('katas', 'steak'));                // false
console.log(scramble('', 'o'));                // false

Solution 2:

Here is the function with some tests:

function scramble(str1, str2) {
  var l = str2.length;
  for (var i = 0; i < l; i++) {
    if (str1.indexOf(str2[i]) > -1) {
      str1 = str1.replace(str2[i], '');
    } else {
      return false;
    }
  }
  return true;
}

function test(str1, str2) {
  console.log('testing "'+str1+'" w/ "'+str2+'": '+(scramble(str1, str2) ? 'true' : 'false'));
}

test('rkqodlw', 'world');
test('cedewaraaossoqqyt', 'codewars');
test('katas', 'steak');

The tests are returning:

testing "rkqodlw" w/ "world": true
testing "cedewaraaossoqqyt" w/ "codewars": true
testing "katas" w/ "steak": false

The function checks if every char of str2 is in str1 and removes it from str1 so that a char from str1 doesn't count twice.


Solution 3:

Split the strings into arrays, and check if every character in the second array is inside the first array.

You probably want to splice of characters as you go, to account for mulitiples of the same character

function scramble(str1, str2) {
    var [arr1, arr2] = [str1.split(''), str2.split('')];
    return arr2.every(x=>arr1.indexOf(x)===-1?false:arr1.splice(arr1.indexOf(x),1));
}

console.log( scramble('rkqwodlw', 'world') );     // true
console.log( scramble('mgoaon', 'moon') );        // true
console.log( scramble('oijhnnassduda', 'moon') ); // false, only one "o"
console.log( scramble('test', 'unicorn') );       // false

Solution 4:

function scramble(str1, str2) {
var [a,b,c] = [str1.split(''),str2.split(''),[]];
for (let i = 0; i < b.length; i++) {
    if (a.indexOf(b[i]) !== -1) {c.push(b[i]), a.splice(a.indexOf(b[i]), 1);}
}
return b.join('') === c.join('');}

Post a Comment for "How To Write A Function That Returns True If A Portion Of Str1 Can Be Rearranged To Str2?"