Can you edit the bold part of the code in the removeDuplicateWithShift() block t
ID: 3777102 • Letter: C
Question
Can you edit the bold part of the code in the removeDuplicateWithShift() block to make it even simpler? The desired output is 1 2 3 4 5 6 7 9 0 0 0, as shown in the page. Thanks!
#include
#include
#include
//using namespace std;
int a[] = { 1, 7, 1, 2, 4, 6, 1, 9, 9, 2 };
int size = sizeof(a)/sizeof(a[0]);
void display() {
for (int i = 0; i < size; i++) {
printf("%d ", a[i]);
}
printf(" ");
}
void insertionSort() {
for(int i = 1; i < size; i++) {
for(int j = i-1; j >= 0; j--){
int temp = a[j];
if(a[j] > a[j+1]){
a[j] = a[j+1];
a[j+1] = temp;
}
else
break;
}
}
}
void deleteDuplicates() {
for(int i = size-1; i >= 0; i--) {
if(a[i] == a[i-1])
a[i] = 0;
}
}
void removeDuplicateWithShift(){
int index = 1;
for(int i=0;i for(int j=(i+1);j if((a[i]^a[j]) ==0) {
a[j] = 0;
}
if((a[j] == 0) && j < size-1){
if(j!=8)
a[j] = a[j+1] == 0? a[j+2]:a[j+1];
a[j+1] =0;
}
}
}
}
int main(){
display();
insertionSort();
printf("After the array is sorted ");
display();
deleteDuplicates();
printf("After the duplicates are removed the element of the array are: ");
display();
removeDuplicateWithShift();
printf("Removes the duplicates and shift the elements to an empty index ");
display();
return 0;
}
Explanation / Answer
#include<stdio.h>
#include<conio.h>
//using namespace std;
int a[] = { 1, 7, 1, 2, 4, 6, 1, 9, 9, 2 };
int size = sizeof(a)/sizeof(a[0]);
int c=0;
void display() {
for (int i = 0; i < size; i++) {
printf("%d ", a[i]);
}
printf(" ");
}
void insertionSort() {
for(int i = 1; i < size; i++) {
for(int j = i-1; j >= 0; j--){
int temp = a[j];
if(a[j] > a[j+1]){
a[j] = a[j+1];
a[j+1] = temp;
}
else
break;
}
}
}
void deleteDuplicates() {
for(int i = size-1; i >= 0; i--) {
if(a[i] == a[i-1])
a[i] = 0;
}
}
/* Added code*/
public int removeDuplicates(input[]){
int j = 0;
int i = 1;
//return if the array length is less than 2
if(input.length < 2){
return input;
}
while(i < input.length){
if(input[i] == input[j]){
i++;
}else{
input[++j] = input[i++];
}
}
int[] output = new int[j+1];
for(int k=0; k<output.length; k++){
output[k] = input[k];
}
return output;
}
/* Added code*/
}
}
int main(){
display();
insertionSort();
printf("After the array is sorted ");
display();
deleteDuplicates();
printf("After the duplicates are removed the element of the array are: ");
display();
int[] output = removeDuplicateWithShift(a[]);
for(c=0;c<output;c++)
printf("%d ",output[c]);
printf("Removes the duplicates and shift the elements to an empty index ");
display();
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.