Wa want a function that gets as parameter one array of integers and its size. Then the function rearranges the array to only have non-repeated integers in the order they appeared and returns the new size of the array.
eg: nums={4,0,4,4,0,23,-8,0}
the function will return the new_size=4 and the new array will have its first 4 elements = {4,0,23,-8}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | #include <stdio.h> int arrange(int *nums, int size){ int new_size=0; int k=0,i,pos=0,next;; //first we must calculate the new_size where all numbers are not repeated for(k=0;k<size-1;k++){ for(i=k+1;i<size;i++) if(nums[k]==nums[i]){ new_size--; break; } } new_size+=size; //now we must put in each cell of the new sized table the corresponding number for(i=0;i<size;i++){ next=0; for(k=0;k<i;k++){ if(nums[i]==nums[k]){ next=1; break;; } } if(next==1) continue; nums[pos++]=nums[i]; if(pos==new_size) break; } return new_size; } int main(){ int nums[]={4,0,4,4,23,0,-8,0}; int new_size; new_size=arrange(nums,8); printf("The new first 4 digits are: %d %d %d %d\nNew size: %d",nums[0],nums[1],nums[2],nums[3],new_size); } |
