mdalmau
mdalmau

Reputation: 81

How to avoid nesting loops when comparing two strings?

I wrote this code that checks if one word can be made from the letters that are available in the other string. For example "wine" can be written using the letters contained in str1 = "kkwlaiern". However I'm looking for a more efficient way of doing this. So far this is my code:

 function scramble(str1, str2) {
  x =str1.split("");
  y =str2.split("");
  var h = 0;


 for (i=0, g = y.length; i<g; i++){
   for (j=0, f= x.length; j<f; j++){
         if (x[j]==y[i]){
           x.splice(j,1);
           h++;
           break;
           }}
 }
 if( h == y.length){
 return true;}
 else{return false;}
} 

How can I write the same function without nesting "for" loops?

Upvotes: 1

Views: 1111

Answers (4)

mdalmau
mdalmau

Reputation: 81

Took me a bit, but here is my solution, turning array elements into property values inside a new Object. Improves efficiency since there's no need for looping through each element of both arrays.

function scramble(str1, str2) {
x= str1.split(""); y= str2.split("");
var arr = new Object();


for(i=0; x.length > i; i++){
arr[x[i]] = (arr[x[i]] || 0) +1;} *//counts occurrence of elements in x and stores them as values inside Object*

for(i =0; y.length > i; i++){ 
arr[y[i]] = (arr[y[i]] || 0)-1;*// reduce value (-1) if y[i] is found in Object*
if (arr[y[i]] < 0){ return false;}} *// returns false if y[i] wasn't found*

return true; *//otherwise returns true.*

}

Upvotes: 0

kaikadi-bella
kaikadi-bella

Reputation: 121

Declare an array of size 26 and initialize it to 0 (index corresponding to the alphabets in English).

Read the bigger string using a for loop and increment it in the array:

a[str1[i]-'a']++

Next, read the smaller string and compare it with the values of the array:

if(a[str2[j]-'a']>0){
     a[str2[j]-'a']--;
}

If the above condition is satisfied for all the elements of str2, then str2 can be derived from str1.

Upvotes: 2

Olavi Sau
Olavi Sau

Reputation: 1649

It's better to just use a Regex

var str1 = 'eve'
var str2 = 'Whatever'
if(st2.match(str1.split('+') && str1.length === str2.length ){
     //handle true
}        

Upvotes: 0

DanielS
DanielS

Reputation: 774

  • Create an array of size 26. Each cell corresponds to a letter.
  • Loop through str1 and put 1 in the array for each letter in the string.
  • Loop trough str2. If you find a letter that has 0 in the array - return false. If you looped through the whole string - return true

Upvotes: 0

Related Questions