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

In C coding language: Write a function that takes two string as inputs and retur

ID: 3829741 • Letter: I

Question

In C coding language:

Write a function that takes two string as inputs and returns the number of occurrences of the permutations of the second string in the first string. The function should also be CASE INSENTIVE. The prototype for this function called countPermutation is given below:

int countPermutation(char s1[], char s2[]);

Ex: If I were to run the following snippet of code calling countPermutation,

int main( int argc, char *argv[]) {

char s1[] = "There was a sudden explosion in the value of the USD in the country Dsumadeupname.";

char s2[] = "USD";

int count;

count = countPermutation(s1, s2);

printf("%d", count);

}

The output of the program would produce: 3 (sud-den, USD, Dsu-madeupname)

Explanation / Answer

#include <stdio.h>
#include <string.h>
#include <ctype.h>

#define MAX 256

int compare(char arr1[], char arr2[])
{
int i;
for (i=0; i<MAX; i++)
if (arr1[i] != arr2[i])
{
return 0;
}
return 1;
}

int countPermutation(char s1[], char s2[])
{
int M = strlen(s2), N = strlen(s1);
int j;
for(j = 0; j < M; j++)
s2[j] = tolower(s2[j]);
for(j = 0; j < N; j++)
s1[j] = tolower(s1[j]);
  
char countP[MAX] = {0}, countTW[MAX] = {0};
int i;
  
  
  
for (i = 0; i < M; i++)
{
(countP[s2[i]])++;
(countTW[s1[i]])++;
}
int count = 0;
// Traverse through remaining characters of pattern
for (i = M; i < N; i++)
{
// Compare counts of current window of text with
// counts of pattern[]
if (compare(countP, countTW))
count++;

// Add current character to current window
(countTW[s1[i]])++;

// Remove the first character of previous window
countTW[s1[i-M]]--;
}

// Check for the last window in text
if (compare(countP, countTW))
count++;
return count;
}

int main( int argc, char *argv[]) {
char s1[] = "There was a sudden explosion in the value of the USD in the country Dsumadeupname.";
char s2[] = "USD";
int count;
count = countPermutation(s1, s2);
printf("%d ", count);
}