In C coding language: Write a function that takes two string as inputs and retur
ID: 3828994 • 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>
int countPermutation(char s1[], char s2[]);
//Ex: If I were to run the following snippet of code calling countPermutation,
int count = 0;
void ChangePosition(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
}
void findAllPermutation(char *s1 , char *s2, int start, int end)
{
int i;
if (start == end){
if(strstr(s1, s2) != NULL)
++count;
}
else
{
for (i = start; i <= end; i++)
{
ChangePosition((s2+start), (s2+i));
findAllPermutation(s1 , s2, start+1, end);
ChangePosition((s2+start), (s2+i));
}
}
}
int countPermutation(char s1[], char s2[]){
int i=0;
while( s2[i] )
{
s2[i] = tolower(s2[i]);
i++;
}
i=0;
while( s1[i] )
{
s1[i] = tolower(s1[i]);
i++;
}
findAllPermutation(s1 , s2, 0, strlen(s2)-1);
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("The count is: %d ", count);
}
Output:-
The count is: 3.