Reputation: 101
My problem is with one function were I need to calculate the euclidean distance from a data file I have, after that I need to get the N lowest numbers given by the euclidean distance.
What I made was an array with the length of all files around 1.000.000
but then it gave me segmentation fault, which was obvious by the way. So what I thought was getting the N value, create an array with N length and just store the N lowest of them all, after that order them by crescent order and then print but iam having difficult on doing the comparison between the values from the euclidean distance and the ones stored in the array.
void calcDist(Nodo *L,int vpesq[],int n)
{
int dist[n],ed;
while(L!=NULL){
x=0;
for(i=0;i<12;i++)
x=x+pow((vpesq[i]-L->caracter[i]),2);
ed=sqrt(x);
}
but now I need to save the N lowest values of ed to dist[n] also the N is given by the user
Upvotes: 1
Views: 155
Reputation: 51443
If you want to save the Nth lowest numbers, you have to do something like this pseudocode:
void calcDist(..)
{ ...
int array_size = //;
int number_add = -1;
for(int i = 0; i < number_of_numbers_to_read; i++)
{
x = // calculate euclidean distance
if(number_add < array_size) // Theres still space in the array
{
number_add++; // a new number in the array
}
// rearrange the array so it will be order again
for(j = 0; j <= number_add; j++)
{
if(array_lower[j] > x) // This is the position to put the value
{
aux = array_lower[j]; // if have to swap than
array_lower[j] = x;
x = aux;
}
}
}
}
Upvotes: 0
Reputation: 15768
You could store the N lowest values like this
void store_lowest_N(int* array, int N, int new_value) {
for (int i=0; i<N; i++) {
if (new_value < array[i]) {
for (j=N-1; j>i; j--) {
array[j] = array[j-1]; // shift the larger values down to make space
}
array[i] = new_value;
break;
}
}
}
void initialize_array(int* array, int N) {
for (int i=0; i<N; i++) {
array[i] = INT_MAX;
}
}
Upvotes: 1
Reputation: 969
If N is not that big, why not make a FOR loop through this N-Array to check if your euclidian distance is smaller than at least one element of the N-Array? If you habe problems with this then this might be caused that your array is not initialized. This means you first have to fill up the array with the very first N numbers of your big file. This happens if you only make an array like this:
int my_array[100];
If you don't assign all 100 values of the array, the non-asigned values will have the value 0 (may depend on compiler) and can cause you problems with you comparison. This is all, if I habe understood your problem right so far.
Upvotes: 0