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

A run in a sequence is a consecutive string of identical elements. Its run-lengt

ID: 3766690 • Letter: A

Question

A run in a sequence is a consecutive string of identical elements. Its run-length is its number of elements. For example, l l o v e e e has four runs of length 2, 1, 1, and 3. Write a program runlength.c that reads a non-empty sequence of at most 100 integers, followed by a non-integer character. The program successively replaces the integers by their run-lengths and then prints the new run-length sequence. It exits once it reaches a sequence of a single run of length 1. Therefore, the program always prints some sequence, and the last sequence it prints is just 1. main stores the integers in an array and then repeatedly calls a function int lenOfRun(int a[], int n) that replaces the numbers in the array a of length n by the lengths of its runs, returns the new array size. For example, if the input array is a=[1,1,1,2,2,3,4], then lenOfRun(a, 7) changes the values in a to a=[3,2,1,1], and returns the length 4.

Example

Array of integers: 1 1 1 2 2 3 4 x
Next: 3 2 1 1
Next: 1 1 2
Next: 2 1
Next: 1 1
Next: 2
Next: 1

Explanation / Answer

Here is your program defined in c

#include <stdio.h>

int lenOfRun(int a[], int n);

int main() {
//Declare variables
int a[100], numberofvalues=0, i;
printf("Array of integers: ");

//While loop to be exited only when a character is read. Counts number of integers.
while (numberofvalues<100 && scanf("%d", &a[numberofvalues])){
numberofvalues++;
}
// Call lenOfRun which modifies array and returns length of new array
numberofvalues = lenOfRun(a, numberofvalues);
// Primary while loop of main function. While array still contains more than one integer it continues to
// call lenOfRun and print new array.
while (numberofvalues > 0)
{
printf("Next ");
for (i=0; i<numberofvalues; i++){
printf("%d ", a[i]);
}
printf(" ");
numberofvalues = lenOfRun(a, numberofvalues);
}
return 0;
}
//lenOfRun reads each integer in the array a[] and counts each consecutive series of integer, replacing
//each run with its length.   
int lenOfRun(int a[], int n)
{
int i, j=0, numberOfRep=0;
//If next integer matches previous increment numberOfRep and repeat
for (i=1; i<=n; i++)
{
if (a[i] == a[i-1])
{
numberOfRep++;
}
//If its the last integer in the array, make whatever bit in the new array we have
//reached (counted by j) equal to current numberOfRep.
else if(i == (n-1))
{
a[j] = numberOfRep;
j++;
}
//make next bit in new array = numberOfRep, reset and repeat
else {
a[j] = numberOfRep;
j++;
numberOfRep = 0;
}
}
return j;
}

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