Solution:read
#include <iostream>
using namespace std;
template <typename AT, typename AS>
void inline printArray(AT p[], AS len)
{
for (size_t i=0; i<len; i++) {
cout << p[i] << " ";
}
cout << endl;
}
size_t unique(int *p, size_t len);
/**
******************************************************************************
*
* Removes duplicate numbers in a sorted array and shrinks array if duplicates
* are found
*
******************************************************************************
*/
int main (int argc, char *argv[])
{
int testa[]= { 1, 2, 4, 6, 7, 8, 9, 12, 15, 19 };
int testb[]= { 1, 1, 1, 4, 5, 9, 9, 10, 10, 12, 15, 18, 20 };
int testc[]= { 1, 2, 4, 5, 6, 8, 8, 8, 8, 8 };
int *p;
size_t len;
p = testa;
len = sizeof(testa)/sizeof(int);
len = unique(p, len);
printArray(p, len);
p = testb;
len = sizeof(testb)/sizeof(int);
len = unique(p, len);
printArray(p, len);
p = testc;
len = sizeof(testc)/sizeof(int);
len = unique(p, len);
printArray(p, len);
return(0);
}
/**
******************************************************************************
*
* Removes duplicate numbers and shrinks array if duplicates are found
*
* @param p - pointer to array
* @param len - original size of array
*
* @return new length of array
*
******************************************************************************
*/
size_t unique(int *p, size_t len)
{
size_t newLen = len;
if (p != NULL)
{
int *q = p;
// prints original content
printArray(q, len);
// camera and action!
int cval = *p;
int *vs, *nxt; // pointer to vacated slot and next number
vs = nxt = p+1;
for (size_t i=0; i<len; i++, nxt++)
{
if (cval != *nxt)
{
cval = *nxt;
if (vs != nxt)
{
*vs = cval;
}
vs++;
}
else {
newLen--;
}
}
}
return newLen;
}
hide solution
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.