You are asked to develop a program which allows the user to enter up to maxSize
ID: 3812578 • Letter: Y
Question
You are asked to develop a program which allows the user to enter up to maxSize characters and which then displays (i) the length of a longest run in the input, and (ii) all indices at which these longest runs occur. What is a run? A run in an array A is an array segment A[j..k] such that A[j], A[j+1], ...., A[k] all have the same value and such that A[j..k+1] is not a run. That is, A[k+1] is either not defined, or does not have the same value as A[k]. For example, if the input characters are a a b b b a a, there are runs ending at indices 1 (namely, aa), 4 (namely, bbb), and 6 (another aa); a longest run - bbb - occurs between indices 2 and 4. A[0] is not itself a run. because A[0..1] is: a segment is not a run if it can be extended to a segment which is a run. Note that the input may have more than one longest run, as, for example, in a a a b b b b a a a a b b b. In this case, the longest run has length 4, and runs of this length occur at indices 3 and 7. It is also possible that the longest run has length 1, as in a b c. In this case, the longest runs occur at indices 0, 1, and 2. The program assumes that the input has at least one character; input is stopped by entering #.Explanation / Answer
#include<stdio.h>
int main()
{
char a[50],len,i=0;
int length(char *,int );
printf("enter the elements :");
while(a[i-1]!='#'){
scanf("%s",&a[i]);
i++;
}
len= length(a,i);
printf("length is %d",len);
return 0;
}
int length(char array[], int n) {
int max = 1;
int curr = 1;
int i,j=0,k=0;
int pmax=1;
int index[10];
for (i = 1; i < n; i++) {
if (array[i - 1] == array[i]) /* the run continues */
{ curr++;
//max = curr > max ? curr : max;
if(curr >= max)
{
max = curr;
index[j]= i-max+1;
j++;
}
else
max=max;
}
else { /* the run was broken */
curr = 1;
}
if(max==1)
{
index[j]=j;j++;
}
} printf(" indices: ");
for(i=0;i<j;i++)
printf(" %d, ",index[i]);
return max;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.