Introduction To Programming In C  Week 6 Answers

                     

Q1. We say that a string ‘s’ is an anagram of another string ‘t’ if the letters in ‘s’ can be rearranged to form ‘t’.

Code:-

#include<stdio.h>
#include<string.h> 
int main()
{
  char a[100],b[100];
  int max=0,i=0; 
  scanf("%s %s",a,b);
  int count1[26] = {0}, count2[26] = {0};
  
  while (a[i] != '\0')

  {

     count1[a[i] - 'a'] ++;
     i++;
   } 
   i = 0;
   while (b[i] != '\0') 
   {
     count2[b[i] -'a']++;
     i++;
   }

   for (i = 0; i<strlen(a); i++) 
   {
      if (count1[i] != count2[i])
      {
        printf("-1");
        return 0;
      }
      if(a[i] == b[i])
         max++;
   }
  printf("%d",max);
  return 0;
}

Q2. In a string, a “run” is a substring with consisting of consecutive
occurrences of the same character. For example, the string
“mississippi” contains the following runs – “ss”, “ss” and “pp”.

Code:-

#include<stdio.h> 
#include<string.h>
int main()
{
  char s[100]; 
  int i,j,max=1,count;
  scanf("%s",s); 
  for(i=0;i<strlen(s)-1;i++)
  {
    j=i+1; 
    count=1;
    while((j<strlen(s))&&(s[i]==s[j])) 
    {
      count++;
      j++;
    }
    if(max<count)
      max=count; 
    i=j-1;
  }
  printf("%d", max);
  return 0;
}

Q3. In this question, you are given two positive integers M and N, where M < N. You may assume that N is less than or equal to 100.

Code:-

#include<stdio.h> 
int main()
{ 
  int i=1,r,d=0,a[100]={0},M,N,p=1; 
  scanf("%d%d",&M,&N); 
  while(i<=N)
  {
    r=(M*p)%N; 
    if(a[r]==0) 
      d++;
    a[r]=a[r]+1; 
    i++; 
    p=p*2;
  } 
  printf("%d",d); 
  return 0;
}