Write a function called deleteRepeats that has a partially filled array of chara
ID: 3544766 • Letter: W
Question
Write a function called deleteRepeats that has a partially filled array of characters as a formal parameter and that deletes all repeated letters from the array. Since a partially filled array requires two arguments, the function will actually have two formal parameters: an array parameter and a formal parameter of type int that gives the number of array positions used. When a letter is deleted, the remaining letters are moved forward to fill in the gap. This will create empty positions at the end of the array so that less of the array is used. Since the formal parameter is a partially filled array, a second formal parameter of type int will tell how many array positions are filled. This seond formal parameter will be a call-by-reference parameter and will be changed to show how much of the array is used after the repeated letters are deleted. For example, consider the following ode:
char a[10];
a[0] = 'a';
a[1] = 'b';
a[2] = 'a';
a[3] = 'c';
int size = 4;
deleteRepeats(a,size);
After this code is executed, the value of a[0] is 'a', the value of a[1] is 'b', the value of a[2] is 'c', and the value of size is 3. (The value of a[3] is no longer of any concern, since the partially filled array no longer uses this indexed variable.) You may assume that the partially filled array contains only lowercase letters. Embed your function in a suitable test program.
Explanation / Answer
#include <iostream>
using namespace std;
void deleteRepeats(char *arr, int *size)
{
for(int i = 0; i < (*size)-1; i++){
for(int j = i+1; j < (*size); j++){
//match found
if(arr[i] == arr[j]){
//once match is found array must be shifted left until it is unique
//if last element just remove it instead of shifting
if(j == (*size)){
arr[j] = NULL;
}
else{
for(int k = j; k < (*size)-1; k++){
arr[k] = arr[k+1];
}
}
(*size)--;
j--; //move back one to recheck to see if replaced is match
}
}
}
}
int main()
{
int size = 10;
char a[10] = {'a','b','a','c','c','c','d','e','b','a'};
cout << "Before function call: ";
for(int i = 0; i < size; i++){
cout << a[i] << " ";
}
deleteRepeats(a, &size);
cout << " After function call: ";
for(int i = 0; i < size; i++){
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.