Skip to content

Instantly share code, notes, and snippets.

@rsnemmen
Created February 19, 2018 21:40
Show Gist options
  • Select an option

  • Save rsnemmen/f36505fd54a86091ee7b24d2edcd7965 to your computer and use it in GitHub Desktop.

Select an option

Save rsnemmen/f36505fd54a86091ee7b24d2edcd7965 to your computer and use it in GitHub Desktop.
Given a desired number, this snippet generates a random array (0<values<1) and outputs the index of the array with value nearest the given float
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
int search(double xref, size_t length, double *x) {
/*
Returns the index corresponding to the element in array x with
value nearest xref.
Inspired on https://codereview.stackexchange.com/a/5146/161148
*/
int i, minindex;
double *diff;
double minimum;
// defines array diff=|x-xref|
diff = (double *)malloc(sizeof(double)*length);
for (i = 0; i < length; i++){
diff[i] = fabs(x[i]-xref);
}
// starting values for search
minimum = diff[0];
minindex=0;
// minimum search
for (i = 1; i < length; ++i) {
if (minimum > diff[i]) {
minimum = diff[i];
minindex=i;
}
}
return minindex;
}
int main(int argc, char *argv[]) {
/*
Given the desired float, this code generates a random array and
outputs the index of the array with value nearest the given float.
*/
int i, j, n=1000;
double *ran;
float arg;
// handle command-line argument
if ( argc != 2 ) {
printf( "usage: %s float \n", argv[0] );
exit(0);
}
sscanf(argv[1], "%f", &arg); // reads command-line argument
// generates array of random floats
ran = (double *)malloc(sizeof(double)*n);
srand(time(NULL));
for (i = 0; i < n; i++){
ran[i] = ((double)rand()/(double)(RAND_MAX));
}
// finds index of element in ran closest to given value fx
j=search(arg,n,ran);
printf("Given value %f, \n Nearest value x[%i]=%f \n", arg, j, ran[j]);
return(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment