• Status: Solved
• Priority: Medium
• Security: Public
• Views: 152

# implementation

Given a value: Lets say:  50.

Assume - I'll call it  X which equals 32.   To 'split' 50.    We'll do X + 18.  (2 numbers)
Similarily for 90:  I'll have X + X + 26 ( 3 numbers)

Need source that'll 'split' the number based on information above and store the numbers in a vector
0
forums_mp
• 3
1 Solution

Commented:
/* Since variable length vectors are not a native type in C, we design
* a simple object that is a vector of integers.
*/
typedef struct _vector {
int *array;      // the array of integers
int num;      // number of integers in the array
int max;      // the size of the current allocation
} *Vector;

/**
* Create a new Vector instance.
*/
Vector newVector()
{
return(calloc(1, sizeof(struct _vector)));
}

/**
* Append integer num to Vector vect
*/
void appendToVector(Vector vect, int num)
{
if (vect != null) {
// Grow the array of integers in chunk sizes of 100, if we run out of room
if (vect.numItems >= vect.allocItems)
vect.array = int * realloc(vect.array, (vect.allocItems += 100)*sizeof(int));
// Append the number to the array
vect.array[numItems++] = num;
}
}

/* Determining the multiples and remainder of X are easy,
* especially using integer division (/) and modular division (%).
* However, since you want to enumerate each multiple in the vector,
* we use simple subtraction in a loop, then append the remainder.
*/

int num = 50;
int x = 32;
Vector vect = newVector();

while (num > x) {
appendToVector(vect, x);
num -= x;
}
if (num)
appendToVector(vect, num);

0

Commented:
This seems easyier:

typedef struct _vector {
int *array;     // the array of integers
int num;     // number of integers in the array
} Vector;

void func(void)
{
Vector vec;
int num=50,x=32;
vec.num=num/x+1;
vec.array=(int *)calloc(num/x,sizeof(int)+1);
memset(vec.array,x,num/x);
vec.array[num/x]=num%x;
}
0

Commented:
>   memset(vec.array,x,num/x);

Memset doesn't work if x > 255

>  vec.array[num/x]=num%x;

Can result in a remainder of 0 added to the vector.

0

Commented:
>           vect.array[numItems++] = num;

Obvious typo.  Should be:

vect.array[vect.numItems++] = num;

0

## Featured Post

• 3
Tackle projects and never again get stuck behind a technical roadblock.