Solved

# implementation

Posted on 2005-04-17
140 Views

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
Question by:forums_mp

LVL 23

Accepted Solution

/* 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

LVL 1

Expert Comment

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

LVL 23

Expert Comment

>   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

LVL 23

Expert Comment

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

Obvious typo.  Should be:

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

0

## Featured Post

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand and use pointers in the C programming language.
The goal of this video is to provide viewers with basic examples to understand and use structures in the C programming language.