Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

How can you create this C++ function for this MyProgrammingLab problem? bool isS

ID: 3562661 • Letter: H

Question

How can you create this C++ function for this MyProgrammingLab problem?

bool isSimilarBag(const string &s, const string &t) ;

// return true iff s and t are the same length and the bag of letters in s is "similar" to the bag of letters in t

// Specifically, let diff(ch, s, t) be the absolute difference of the number of occurrences of ch in s and t.

// Then we want diff('a',s,t) + diff('b',s,t) + ... + diff('z',s,t) <= L/3, where L is the common length of s and t.

// precondition: s and t contain only lowercase letters {'a'... 'z'}

I don't want you to write the entire program or any other functions

Here is my source code for this function:

bool isSimilarBag(const string &s, const string &t)
{
   int s_diff[26] = {0};
   int t_diff[26] = {0};
   if(s.length() != t.length())
   {  
       return false;
   }
   for(int i = 0; i < s.length(); i++)
   {
       s_diff[s[i]-'a']++;
   }
   for(int i = 0; i < s.length(); i++)
   {
       t_diff[s[i]-'a']++;
   }
   int sum = 0;
   for(int k = 0; k < 26; k++)
   {
       sum = sum + (s_diff[k] > t_diff[k] ? (s_diff[k]-t_diff[k])
           : (t_diff[k]-s_diff[k]));
   }
   return 3*sum <= s.length();
}

The output I am getting is 0, but I also want to get 1.

Can someone please just post the correct code for this function?

Explanation / Answer

You are doing

for(int i = 0; i < s.length(); i++)
   {
       t_diff[s[i]-'a']++;
   }

What you have to do is

for(int i = 0; i < t.length(); i++)
   {
       t_diff[t[i]-'a']++;
   }

That is why you are geting output zero because s_diif and t_diff are same.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote