I am working on a code project that checks if all the characters in str1str1
can be arranged to form another string (str2str2
). If all the characters in str2str2
are present in str1 str1
(including any repeated characters in str2str2
, i.e. if str2str2
has two 'a' characters, str1str1
must correspondingly have two as well), then the function returns true
.
forFor example, here are some test cases below and the intended return:
str1 = 'rkqodlw'
str2 = 'world'
Expected: true
str1 = 'cedewaraaossoqqyt'
str2 = 'codewars'
Expected: true
str1 = 'katas'
str2 = 'steak'
Expected: false
str1 = 'scriptjava'
str2 = 'javascript'
Expected: true
str1 = 'rkqodlw' str2 = 'world' Expected: true str1 = 'cedewaraaossoqqyt' str2 = 'codewars' Expected: true str1 = 'katas' str2 = 'steak' Expected: false str1 = 'scriptjava' str2 = 'javascript' Expected: true
I have a working code solution below, but i'dI'd like to refactor for optimal performance as there are a quite a number of random tests (of unknown length) that the code must test against and my code isn't completing the tests in the recommended timeframe.
function stringscrambling(str1, str2) {
var arr1 = str1.split('');
var arr2 = str2.split('');
var index;
var l = arr2.length;
while (l--) {
index = arr1.indexOf(arr2[l]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
function stringscrambling(str1, str2) {
var arr1 = str1.split('');
var arr2 = str2.split('');
var index;
var l = arr2.length;
while (l--) {
index = arr1.indexOf(arr2[l]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
for (var i = 0, l = arr2.length; i < l ; i++) {
index = arr1.indexOf(arr2[i]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
for (var i = 0, l = arr2.length; i < l ; i++) {
index = arr1.indexOf(arr2[i]);
if (index > -1) {
arr1.splice(index, 1);
} else {
return false;
};
}
return true;
}
but tried the whilewhile
-loop in reverse as I readread that specific looping would offer a bit better in terms of benchmarked performance. https://blogs.oracle.com/greimer/entry/best_way_to_code_a
The change in loop offered a negligible performance upgrade.