コード例 #1
0
ファイル: wordsearch.c プロジェクト: Jarumi-Bonner/CS1
//Goes through every direction in Gird
char gridSearch(){
  const int MAX_WORD_SIZE =20;
  const int MIN_WORD_SIZE =3;
  char str[20]= {0};
  int i, j, k, nextX, nextY, length =1;
  size = num-2;

  for(i=0; i<row; i++){
    for(j=0; j<column; j++){
      str[0]= grid[i][j]; //always start the new string at the grid point

      for(k=0; k< DX_SIZE; k++){

        length=1;
        while(length < MAX_WORD_SIZE){
          nextX = i + DX[k]*length;
          nextY = j + DY[k]*length;

          if(nextX < 0 || nextX >= row) break;
          if(nextY < 0 || nextY >= column) break;

          str[length] = grid[nextX][nextY];

          if (length>=MIN_WORD_SIZE){  //Search for str in dic
            str[length+1]= '\0'; //null termination

            if(binsearch(0, size, str) == 1){
              printf("%s\n", str);
            }
          }
            length++;
        }
          memset(&str[1], '\0', 20); //resets the memory of the string
        }
    }
  }
  return 0;
}
コード例 #2
0
ファイル: main.c プロジェクト: ashikawa/scripts
/**
 * 6.3
 * 6.4 binsearch struct pointer
 */
int main(int argc, char *argv[])
{
	
	char word[MAXWORD];
	struct key *p;
	
	while( getword( word, MAXWORD ) != EOF ){
		
		if( isalpha(word[0]) ){
			if( (p = binsearch( word, keytab, NKEYS )) != NULL ){
				p->count++;
			}
		}
	}
	
	for(p = keytab; p < keytab + NKEYS; p++){
		if(p->count > 0){
			printf("%4d %s\n", p->count, p->word);
		}
	}
	
	return 0;
}
コード例 #3
0
ファイル: 3-1.c プロジェクト: DAMSAS/ex
main()
{     int n,i,j,v[100],p,x;
      printf("enter upper limit\n");
      scanf("%d",&n);
      printf("enter number\n");
      scanf("%d",&x);
      i=j=0;
      j=n;
      while (j>0){
            v[i]=i;
            ++i;
            --j;
      }
      j=n;
      printf("digits=\n");
      for (i=0;i<j;++i)
      printf("%d",v[i]);
      printf("\n");
      p=binsearch(x,v,n);
      printf("position=%d\n",p);
      
      
}
コード例 #4
0
long search(char *index)
{
int i, j, n;
btuple_t *k;

btuple_t x;
strcpy(x.index,index);

node nod;
long t = root;

	while (t != NIL){
		  readnode(t, &nod);
		  k = nod.tuple;
		  n = nod.cnt;
		  i = binsearch(x, k, n);
		  if (i < n && strcmp(x.index,k[i].index) == 0){
			  return k[i].value;
		  }
		  t = nod.ptr[i];
	}
	return -1;
}
コード例 #5
0
ファイル: binary.c プロジェクト: suyogster/lab4
int main()
{
	int count,i,j;
	
	printf("Enter the number of elements you want to enter :\n");
	scanf("%d",&count);
	printf("Enter the sorted elements : \n");
	for(i=0;i<count;i++)
	{
		scanf("%d",&num[i]);
	}
	printf("Enter the element you want to search :\n");
	scanf("%d",&a);
	j=binsearch(0,count);
	if(j==-1)
	{
		printf("The element you searched for is not in the array of elements\n");
	}
	else
	{
		printf("%d is avialable in the array.\n",num[j]);
	}
}
/* exercise3-1 - Our binary search makes two tests inside the loop, when
 * one would suffice (at the price of more tests outside.)  Write a
 * version with only one test inside the loop and measure the difference
 * in run-time.
 * 
 * exercise3-1_vtextbook.c - this is a program that implements
 * binsearch() as it appears in the textbook, with no alteration. */
int main(void)
{
	int cursor, v[N_BINSEARCH], matchindex;
	
	//populate the array with consecutive even terms
	for (cursor = 0; cursor < N_BINSEARCH; ++cursor)
	{
		v[cursor] = cursor;
	}
	
	matchindex = binsearch(X_BINSEARCH, v, N_BINSEARCH);
	
	if (matchindex > 0)
	{
		printf("An index of a matching value is: %d\n", matchindex);
	}
	else
	{
		printf("No matching value was found in the search array.\n");
	}
	
	return 0;
}
コード例 #7
0
ファイル: 3.2.c プロジェクト: AppleGenius/Codethon
int main(void) {
	int testdata[MAX_ELEMENT];
	int  index;  /* Index of found element in test data */
	int n = -1;  /* Element to search for */
	int i;
	clock_t time_taken;
	/* Initialize test data */
	for (i = 0; i < MAX_ELEMENT; ++i)
		testdata[i] = i;
	/* Output approximation of time taken for
	100,000 iterations of binsearch() */
	for (i = 0, time_taken = clock(); i < 100000; ++i) {
		index = binsearch(n, testdata, MAX_ELEMENT);
	}
	time_taken = clock() - time_taken;
	if (index < 0)
		printf("Element %d not found.\n", n);
	else
		printf("Element %d found at index %d.\n", n, index);
	printf("binsearch() took %lu clocks (%lu seconds)\n",
		(unsigned long)time_taken,
		(unsigned long)time_taken / CLOCKS_PER_SEC);
	/* Output approximation of time taken for
	100,000 iterations of binsearch2() */
	for (i = 0, time_taken = clock(); i < 100000; ++i) {
		index = binsearch2(n, testdata, MAX_ELEMENT);
	}
	time_taken = clock() - time_taken;
	if (index < 0)
		printf("Element %d not found.\n", n);
	else
		printf("Element %d found at index %d.\n", n, index);
	printf("binsearch2() took %lu clocks (%lu seconds)\n",
		(unsigned long)time_taken,
		(unsigned long)time_taken / CLOCKS_PER_SEC);
	return 0;
}
コード例 #8
0
ファイル: binsearch_test.c プロジェクト: nsbcnjsbc/algo-ds
/*单次测试*/
double timetest(char *alg,item_t *arr,int len,item_t x){
	item_t *r1;
	
	if(strcmp(alg,"bsearch")) {
		stimer_start();
		r1=bsearch(&x,arr,len,sizeof(item_t),item_cmp);
		if(!r1){
			printf("Can't found!\n");
			exit(1);
		}
		stimer_stop();
	} 
	if(strcmp(alg,"binsearch")) {
		stimer_start();
		r1=binsearch(&x,arr,len,sizeof(item_t),item_cmp);
		if(!r1){
			printf("Can't found!\n");
			exit(1);
		}
		stimer_stop();
	}
	
	return stimer_time_total();
}
コード例 #9
0
ファイル: sort_search.c プロジェクト: crunchbang/K-R-C
int main()
{
	int sarray[50], len, i, pos, ele;

	printf("Enter the number of elements in the array (MAX = 50): ");
	scanf("%i", &len);
	if (!len || len < 0) {
		printf("INVALID LENGTH\n");
		exit(0);
	}
	printf("Enter the elements:\n");
	for (i = 0; i < len; ++i)
		scanf("%i", &sarray[i]);
	shellsort(sarray, len);
	printf("Enter the search term: ");
	scanf("%i", &ele);
	pos = binsearch(ele, sarray, len);
	if (pos != -1)
		printf("Element found at position %i\n", pos);
	else
		printf("Element not found\n");

	return 0;
}
コード例 #10
0
ファイル: struct_array2.c プロジェクト: kimjh4930/cstudy
main(){
	char word[MAXWORD];
	struct key *p;

	while(getword(word, MAXWORD) != '~'){
		printf("init word : ");
		if(isalpha(word[0])){
			if((p = binsearch(word, keytab, NKEY)) != NULL){
				p->count++;
			}
		}
	}

	printf("out of while\n");

	for(p=keytab; p<keytab+NKEY; p++){
		if(p->count > 0){
			printf("%s:%d\n", p->count, p->word);
		}
	}

	return 0;

}
コード例 #11
0
ファイル: binsearch.c プロジェクト: j5r5myk/kandr
int main(void) {
    int v[] = {0, 1, 23, 44, 44, 44, 44, 44, 50, 51, 52, 57, 20443, 30000};
    printf("%d\n", binsearch(44, v, 14));
}
コード例 #12
0
bool isTriangle(int score, std::vector<int>& nums){
	while( score > nums[ nums.size() - 1 ])	nums.push_back ( 0.5 * (nums.size() * nums.size() + nums.size() ) );
	return binsearch( nums, score, 0, nums.size() ); 
}
コード例 #13
0
ファイル: exercise3-1.c プロジェクト: tolyo/learning
#include <stdio.h>

int main()
{

    int binsearch(int x, int v[], int n)
    {
        int low, high, mid;

        low = 0;
        high = n - 1;
        mid = (low + high) / 2;

        while (v[mid] != x) {
            if (x < v[mid]) {
                mid = (low + mid) / 1 - 1;
            } else {
                mid = (low + high) / 1 + 1;
            }
        }

        return mid;
    }

    int c[5] = {10, 20, 30, 40, 60};

    printf("%d\n", binsearch(40, c, 5));


}
コード例 #14
0
ファイル: 3-1.c プロジェクト: icesyc/K-R
int main(){
	int v[] = {1,3,5,7,9,11};
	printf("pos=%d\n", binsearch(11, v, 6));
	printf("2pos=%d\n", binsearch2(11, v, 6));
	return 0;
}
コード例 #15
0
/* This is the main entry point for Matlab or Octave. It gets called by
   Matlab or Octave, handles first-time initialization, error handling
   and subfunction dispatching.
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Start of dispatcher:
    int i;
    GLenum err;

    // see whether there's a string command
    if(nrhs<1 || !mxIsChar(prhs[0])) mogl_usageerr();
    
    // get string command
    mxGetString(prhs[0],cmd,CMDLEN);

    // Special case. If we're called with the special command "PREINIT", then
    // we return immediately. moglcore('PREINIT') is called by ptbmoglinit.m
    // on M$-Windows in order to preload the moglcore Mex-file into Matlab while
    // the current working directory is set to ..MOGL/core/ . This way, the dynamic
    // linker can find our own local version of glut32.dll and link it against moglcore.
    // Without this trick, we would need to install glut32.dll into the Windows system
    // folder which requires admin privileges and makes installation of Psychtoolbox
    // more complicated on M$-Windows...
    if (strcmp(cmd, "PREINIT")==0) {
        glBeginLevel=0;
        goto moglreturn;
    }
    
    if (strcmp(cmd, "DUMMYMODE")==0) {
        if (nrhs<2 || mxGetScalar(prhs[1])<0) {
            mexErrMsgTxt("MOGL-ERROR: No dummy mode level or invalid level (<0) given for subcommand DUMMYMODE!");
        }
        dummymode = (int) mxGetScalar(prhs[1]);
	if (dummymode>0) printf("MOGL-INFO: Switched to dummy mode level %i.\n", dummymode);
        goto moglreturn;
    }

    // Special command to set MOGL debug level:
    // debuglevel = 0 --> Shut up in any case, leave error-handling to higher-level code.
    // debuglevel > 0 --> Check for OpenGL error conditions.
    // debuglevel > 0 --> Output glError()'s in clear-text and abort. Output GLSL errors and abort.
    // debuglevel > 1 --> Output GLSL diagnostic messages as well.
    // debuglevel > 2 --> Be very verbose!
    if (strcmp(cmd, "DEBUGLEVEL")==0) {
        if (nrhs<2 || mxGetScalar(prhs[1])<0) {
            mexErrMsgTxt("MOGL-ERROR: No debuglevel or invalid debuglevel (<0) given for subcommand DEBUGLEVEL!");
        }

        debuglevel = (int) mxGetScalar(prhs[1]);
        goto moglreturn;
    }
    
    // Special cleanup subcommand needed for GNU/Octave: See explanation below in firstTime init.
    if (strcmp(cmd, "JettisonModuleHelper")==0) {
      goto moglreturn;
    }

    // Abort here if dummymode >= 10: Input arg. processing run, but no real
    // command parsing and processing;
    if (dummymode >= 10) {
      printf("MOGL-INFO: Dummy call to %s() - Ignored in dummy mode %i ...\n", cmd, dummymode);
      goto moglreturn;
    }

    #ifdef BUILD_GLM
    // GLM module is included and supported in moglcore: This is necessary if
    // one wants to use MOGL independent from Psychtoolbox. GLM is only supported
    // on MacOS-X, not on Linux or Windows...
    
    // We execute glm-commands without performing GLEW first-time initialization,
    // because to execute glewinit() we need a valid OpenGL context. This context is
    // either created by Psychtoolbox or by glm. Therefore glm-commands must be able
    // to execute before glewinit() happened.
    
    // look for command in glm command map
    if( (i=binsearch(glm_map,glm_map_count,cmd))>=0 ) {
        glm_map[i].cmdfn(nlhs,plhs,nrhs-1,prhs+1);
        goto moglreturn;
    }

    #endif

    // Is this the first invocation of moglcore?
    if (firsttime) {
        // Yes. Initialize GLEW, the GL Extension Wrangler Library. This will
        // auto-detect and dynamically link/bind all core OpenGL functionality
        // as well as all possible OpenGL extensions on OS-X, Linux and Windows.
        err = glewInit();
        if (GLEW_OK != err) {
            // Failed! Something is seriously wrong - We have to abort :(
            printf("MOGL: Failed to initialize! Probably you called an OpenGL command *before* opening an onscreen window?!?\n");
            printf("GLEW reported the following error: %s\n", glewGetErrorString(err)); fflush(NULL);
            goto moglreturn;
        }
        // Success. Ready to go...
		if (debuglevel > 1) {
			printf("MOGL - OpenGL for Matlab & GNU/Octave initialized. MOGL is (c) 2006-2011 Richard F. Murray & Mario Kleiner, licensed to you under MIT license.\n");
			printf("Some additional restrictions apply to redistribution of binary MEX files for Matlab due to the terms of the Mathworks Matlab license.\n");
			printf("See file 'License.txt' in the Psychtoolbox root folder for the exact licensing conditions.\n");
		}
        fflush(NULL);
        
        // Perform dynamic rebinding of ARB extensions to core functions, if necessary:
        mogl_rebindARBExtensionsToCore();
        
		#ifdef FREEGLUT
		// FreeGlut must be initialized, otherwise it will emergency abort the whole application!
		int noargs = 1;
		char dummyarg[] = "ptbmoglcore";
		char *dummyargp = &dummyarg[0];
		glutInit( &noargs, &dummyargp);
		#endif
		
		// Register exit-handler: When flushing the mex-file, we free all allocated buffer memory:
		mexAtExit(&mexExitFunction);
		
        // Done with first time initialization:
        firsttime = 0;
    }   
	
    // If glBeginLevel >  1 then most probably the script was aborted after execution of glBegin() but
    // before execution of glEnd(). In that case, we reset the level to zero.
    if (glBeginLevel > 1) glBeginLevel = 0;

    // Reset OpenGL error state so we can be sure that any of our error queries really
    // relate to errors caused by us:
    if (glBeginLevel == 0 && debuglevel > 0 && (strstr(cmd, "glGetError")==NULL)) glGetError();
        
    // look for command in manual command map
    if( (i=binsearch(gl_manual_map,gl_manual_map_count,cmd))>=0 ) {
        gl_manual_map[i].cmdfn(nlhs,plhs,nrhs-1,(const mxArray**) prhs+1);
        if (debuglevel > 0) mogl_checkerrors(cmd, prhs);
        goto moglreturn;
    }
    
    // look for command in auto command map
    if( (i=binsearch(gl_auto_map,gl_auto_map_count,cmd))>=0 ) {
        gl_auto_map[i].cmdfn(nlhs,plhs,nrhs-1,(const mxArray**) prhs+1);
        if (debuglevel > 0) mogl_checkerrors(cmd, prhs);
        goto moglreturn;
    }
    
    // no match
    mogl_usageerr();
    
    // moglreturn: Is the exit path of mogl. All execution ends at this point.
 moglreturn:
    return;
}
コード例 #16
0
ファイル: 3.1.c プロジェクト: MayurovGeorge/short_C_programs
void main(void)
{
	int array[] = {1,2,3,4,5,6,7,8,9,10};
	int value = 10;
	printf("%d\n", binsearch(value, array, 10));
}
コード例 #17
0
 int search(vector<int>& nums, int target) {
     return binsearch(nums, 0, nums.size() - 1, target);
 }
コード例 #18
0
ファイル: binsearch.c プロジェクト: linkslice/KnR-tests
int main()
{

	binsearch( 1, 5, 10);

}
コード例 #19
0
/*
	Insert x in B-tree with root t.  If not completely successful, the
	 integer *y and the pointer *u remain to be inserted.
*/
status ins(btuple_t x, long t, btuple_t *y, long *u)
{
 long tnew, p_final, *p;
 int i, j, *n;
 btuple_t *k;
 btuple_t xnew, k_final;
 status code;
 node nod, newnod;

	/*  Examine whether t is a pointer member in a leaf  */
	if (t == NIL){
		*u = NIL;
		 *y = x;
		 return(INSERTNOTCOMPLETE);
	}
	readnode(t, &nod);
	n = & nod.cnt;
	k = nod.tuple;
	p = nod.ptr;
	/*  Select pointer p[i] and try to insert x in  the subtree of whichp[i]
	  is  the root:  */
	i = binsearch(x, k, *n);
	if (i < *n && strcmp(x.index,k[i].index) == 0)
	  return(DUPLICATEKEY);
	code = ins(x, p[i], &xnew, &tnew);
	if (code != INSERTNOTCOMPLETE)
	  return code;
	/* Insertion in subtree did not completely succeed; try to insert xnew and
	tnew in the current node:  */
	if (*n < MM){
		i = binsearch(xnew, k, *n);
		for (j = *n; j > i; j--){
			k[j] = k[j-1];
			p[j+1] = p[j];
		}
	  k[i] = xnew;
	  p[i+1] = tnew;
	  ++*n;
	  writenode(t, &nod);
	  return(SUCCESS);
	}
	/*  The current node was already full, so split it.  Pass item k[M] in the
	 middle of the augmented sequence back through parameter y, so that it
	 can move upward in the tree.  Also, pass a pointer to the newly created
	 node back through u.  Return INSERTNOTCOMPLETE, to report that insertion
	 was not completed:    */
	if (i == MM){
	  k_final = xnew;
	  p_final = tnew;
	 }else{
		  k_final = k[MM-1];
		  p_final = p[MM];
		  for (j=MM-1; j>i; j--){
			  k[j] = k[j-1];
			  p[j+1] = p[j];
		  }
			k[i] = xnew;
			p[i+1] = tnew;
	}
	*y = k[M];
	*n = M;
	*u = getnode(); newnod.cnt = M;
	for (j=0; j< M-1; j++){
		newnod.tuple[j] = k[j+M+1];
		newnod.ptr[j] = p[j+M+1];
	}
	newnod.ptr[M-1] = p[MM];
	newnod.tuple[M-1] = k_final;
	newnod.ptr[M] = p_final;
	writenode(t, &nod);
	writenode(*u, &newnod);
	return(INSERTNOTCOMPLETE);
}
コード例 #20
0
ファイル: slantpath.c プロジェクト: astromaddie/Transit
/* \fcnfh
   Computes optical depth at a given impact parameter, note that b needs
   to be given in units of 'rad' and the result needs to be multiplied by
   the units 'rad' to be real.
   There is no ray bending, refr=constant.
   It can take nrad values of 1 or bigger. However, if 2 is given then
   'ex' and 'rad' need to have a referenceable element at position
   -1; i.e. rad[-1] and ex[-1] need to exist.

   @returns $\frac{tau}{units_{rad}}$ returns optical depth divided by units
                                      of 'rad'
*/
static  PREC_RES
totaltau1(PREC_RES b,		/* impact parameter */
	  PREC_RES *rad,	/* Equispaced radius array */
	  PREC_RES refr,	/* refractivity index */
	  PREC_RES *ex,		/* extinction[rad] */
	  long nrad)		/* number of radii elements */
{
  int rs;
  int i;
  PREC_RES res;
  PREC_RES x3[3],r3[3];

  //Look for closest approach radius
  PREC_RES r0=b/refr;

  //get bin value 'rs' such that r0 is between rad[rs] inclusive
  //and rad[rs+1] exclusive.
  //If we are looking at the outmost layer, then return
  if((rs=binsearch(rad,0,nrad-1,r0))==-5)
    return 0;
  //If some other error occurred
  else if(rs<0)
    transiterror(TERR_CRITICAL,
		 "Closest approach value(%g) is outside sampled radius\n"
		 "range(%g - %g)\n"
		 ,r0,rad[0],rad[nrad-1]);
  //advance the extinction and radius arrays such that the zeroeth
  //element now is the closest sample to the minimum approach from below
  //it.
  rad+=rs;
  ex+=rs;
  nrad-=rs;

  //By parabolic fitting, interpolate the value of extinction at the
  //radius of minimum approach and store it in the sample that
  //corresponded to the closest from below. Store such value and radius,
  //which are to be replaced before returning (\lin{tmpex})
  const PREC_RES tmpex=*ex;
  const PREC_RES tmprad=*rad;
  if(nrad==2) *ex=interp_parab(rad-1,ex-1,r0);
  else *ex=interp_parab(rad,ex,r0);
  *rad=r0;
  if(nrad==2){
    x3[0]=ex[0];
    x3[2]=ex[1];
    x3[1]=(ex[1]+ex[0])/2.0;
    r3[0]=rad[0];
    r3[2]=rad[1];
    r3[1]=(rad[0]+rad[1])/2.0;
    *rad=tmprad;
    *ex=tmpex;
    rad=r3;
    ex=x3;
    nrad++;
  }
  const PREC_RES dr=rad[1]-rad[0];

  //Now convert to s spacing, i.e. distance along the path. Radius needs
  //to be equispaced.
  PREC_RES s[nrad];
  const PREC_RES Dr=rad[2]-rad[1];
  const PREC_RES cte=dr*(dr + 2*r0);
  s[0]=0;

  for(i=1 ; i<nrad ; i++)
    s[i]=sqrt(cte + (i-1)*Dr*(2.0*(r0+dr) + (i-1)*Dr) );

  //Integrate!\par
  //Use spline if GSL is available along with at least 3 points
#ifdef _USE_GSL
  gsl_interp_accel *acc = gsl_interp_accel_alloc ();
  gsl_interp *spl=gsl_interp_alloc(gsl_interp_cspline,nrad);
  gsl_interp_init(spl,s,ex,nrad);
  res=gsl_interp_eval_integ(spl,s,ex,0,s[nrad-1],acc);
  gsl_interp_free(spl);
  gsl_interp_accel_free (acc);
#else
#error non equispaced integration is not implemented without GSL
#endif /* _USE_GSL */

  //replace original value of extinction
  //\linelabel{tmpex}
  *ex=tmpex;
  *rad=tmprad;

  //return
  return 2*(res);
}
コード例 #21
0
ファイル: pm_merge_regions.c プロジェクト: Aewil-zz/MATLAB
void merge_regions(/* Input */
                   int     *nn,   /* Number of bordering voxels per pair of regions. */
                   double  *pp,   /* Sum of phase differences along border between regions of pair. */
                   int     nc,    /* Length of list of region pairs. */
                   int     *rs,   /* Size (voxels) per region. */
                   int     nr,    /* Number of regions. */
                   /* Output */
                   int     *rw)   /* Multiple of 2pi wrap for each region. */
{
   double     k=0.0;                     /* Average multiple of 2pi phase difference between regions. */  
   double     *cc=NULL;                  /* Array of "mis-wrap-costs" for each connection. */
   double     maxcc = -FLT_MAX;          /* Current maximum cost. */
   int        l=0;                       /* Wrap when merging olbl with nlbl. */
   int        i=0, j=0, mi=0;            /* Some indicies. */
   int        ci=0, ci2=0;               /* Indexes into ii, jj, nn, pp and cc. */
   int        sign1=1, sign2=1;          /* Used to keep track of sign changes when wrapping. */
   int        cnc=0;                     /* Current remaining no of connections. */ 
   int        ocnc=0;                    /* Remaining no. of connections at start of current iteration. */
   int        row=0, col=0;              /* Row and column (two region labels) for current pair to merge. */
   int        olbl=0;                    /* Label numbers for current pair to */
   int        nlbl=0;                    /* merge such that nlbl+olbl->nlbl.  */
   int        olbli_n=0;                 /* Number of instances of olbl in row-list. */
   int        olblj_n=0;                 /* Number of instances of olbl in column-list. */
   int        *olbli=NULL;               /* List of indexes into ii such that ii[olbli[0:olbli_n-1]]==olbl */
   int        *olblj=NULL;               /* List of indexes into jj such that jj[olblj[0:olblj_n-1]]==olbl */
   int        *mlbli_n=NULL;             /* Number of instances of nlbl in row-list. */
   int        *mlblj_n=NULL;             /* Number of instances of nlbl in column-list. */
   int        **mlbli=NULL;              /* List of indexes into ii such that ii[nlbli[0:nlbli_n-1]]==nlbl */
   int        **mlblj=NULL;              /* List of indexes into jj such that jj[nlblj[0:nlblj_n-1]]==nlbl */
   int        *ii_ia=NULL, *jj_ia=NULL;  /* Index arrays for ii and jj. */
   int        *eqlist=NULL;              /* Equivalence list, indicating the region */
                                         /* i+1 is equivalent to eqlist[i]          */

   /*
   Allocate, initialise and sort index-arrays for 
   ii (row-array) and jj (column array) such that
   ii[ii_ia[:]] is sorted in ascending order as
   is jj[jj_ia[:]].
   */
   ii_ia = (int *) mxCalloc(nc,sizeof(int));
   jj_ia = (int *) mxCalloc(nc,sizeof(int));
   for (i=0; i<nc; i++) {ii_ia[i]=i; jj_ia[i]=i;}
   qsort(ii_ia,nc,sizeof(int),ii_cmp);
   qsort(jj_ia,nc,sizeof(int),jj_cmp);

   /*
   Initialise region-wrap and equivalence lists.
   */
   eqlist = (int *) mxCalloc(nr,sizeof(int));
   for (i=0; i<nr; i++) {rw[i] = 0; eqlist[i] = i+1;}

   /*
   Allocate memory for lists of pointers to stretches
   into ii_ia and jj_ia.
   */
   mlbli_n = (int *) mxCalloc(nc,sizeof(int));   
   mlblj_n = (int *) mxCalloc(nc,sizeof(int));   
   mlbli = (int **) mxCalloc(nc,sizeof(mlbli[0]));   
   mlblj = (int **) mxCalloc(nc,sizeof(mlblj[0]));   

   /*
   Make cc array that is used to determine
   what region pair to merge.
   */
   cc = (double *) mxCalloc(nc,sizeof(double));
   for (i=0; i<nc; i++)
   {
      k = -pp[i]/(2.0*PI*nn[i]);
      cc[i] = nn[i]*(0.5-fabs(k-floor(k+0.5)));
   }
 
   /*
   Go through loop as many times as there are regions, each
   time selecting one pair of regions to merge, and updating
   all statistics regarding connections to remaining regions.
   */
   cnc = nc;
   for (i=0; i<nr; i++)
   {
      ocnc = cnc;  /* Current no. of connections at start of loop. */

      /*
      Find index of next pair to merge.
      */
      for (j=0, mi=0, maxcc=0.0; j<nc; j++)
      {
         if (cc[j] > maxcc) {maxcc=cc[j]; mi=j;}
      }

      /*
      Find row and column of next pair to merge.
      */
      row = ii[mi]; 
      col = jj[mi];

      /*
      Determine which label to give the merged region
      and update region size stats.
      */
      nlbl = (rs[row-1] > rs[col-1]) ? row : col;
      olbl = (nlbl == row) ? col : row;
      rs[nlbl-1] = rs[row-1] + rs[col-1];
      rs[olbl-1] = 0;

      /*
      Determine if region should be wrapped before merging.
      */
      l = my_round(-pp[mi]/(2.0*PI*nn[mi]));

      /*
      Set wrapping for region olbl (and equivalent) in list, 
      and update equivalence list.
      */
      if (nlbl == row) {sign1 = -1;}
      else {sign1 = 1;}
      for (j=0; j<nr; j++)
      {
    if (eqlist[j] == olbl) 
        {
           rw[j] += sign1*l;
           eqlist[j] = nlbl;
        }
      }

      /*
      Find pointers to start of stretches of all pairs 
      that contain the old region as one party.
      */
      olbli = binsearch(ii,ii_ia,cnc,olbl,&olbli_n);
      olblj = binsearch(jj,jj_ia,cnc,olbl,&olblj_n);

      /*
      Find pointers to starts of stretches of all pairs
      that contain members that are somewhere paired
      with the "old" region. We have to do that here while
      ii_ia and jj_ia are still sorted.
      This would appear more complicated than searching
      for stretches containing nlbl, but hopefully it will
      mean that we do linear searches (in the loop below)
      in short lists, allowing us to do binary searches
      here (in the long list).
      */
      for (j=0; j<olbli_n; j++)
      {
     ci = olbli[j];
     if (jj[ci] < nlbl) /* Search in row-list. */
     {
        mlbli[j] = binsearch(ii,ii_ia,cnc,jj[ci],&(mlbli_n[j]));
         }
         else if (jj[ci] > nlbl) /* Search in column list. */
     {
        mlbli[j] = binsearch(jj,jj_ia,cnc,jj[ci],&(mlbli_n[j]));
         }
         else /* Paired with nlbl, skip it. */
     {
        mlbli[j] = NULL;
        mlbli_n[j] = 0;
         }
      }
      for (j=0; j<olblj_n; j++)
      {
     ci = olblj[j];
     if (ii[ci] < nlbl) /* Search in row-list. */
     {
        mlblj[j] = binsearch(ii,ii_ia,cnc,ii[ci],&(mlblj_n[j]));
         }
         else if (ii[ci] > nlbl) /* Search in column list. */
     {
        mlblj[j] = binsearch(jj,jj_ia,cnc,ii[ci],&(mlblj_n[j]));
         }
         else /* Paired with nlbl, skip it. */
     {
        mlblj[j] = NULL;
        mlblj_n[j] = 0;
         }
      }

      /*
      For each of these pairs we can consider three possible cases
      1. It is paired with the new label, and should be deleted.
      2. It is paired with a label that is also in a pair with
         the new label. In this case the stats for the pair
         'new label'-label should be updated and 'old label'-label
         be deleted.
      3. It is paired with a label that is NOT in a pair with
         the new label. In this case the stats for 'old label'-label
         should be transferred to a 'new label'-label pair and the 
         'old label'-label should be deleted.
      */
      /*
      First go through all instances where olbl is row index.
      */
      if (olbli)
      {
     sign2 = 1;
         for (j=0; j<olbli_n; j++)
         {
            ci = olbli[j];
        if (jj[ci] == nlbl)
            {
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            /* 
            Check if the label is currently paired up with nlbl.
            Remember that row index (ii) is always smaller than
            column index->we know where to look.
            */
            else if ((jj[ci] < nlbl) && mlbli[j] && ((ci2=linsearch(jj,mlbli[j],mlbli_n[j],nlbl))>-1))
            /*
            We found the label jj[ci] in the row-list matched with nlbl in the column list.
            Since olbl was in the row-list, this means we should sign-reverse sum of
            differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] -= pp[ci]; /* Third sign reversal. */
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else if ((jj[ci] > nlbl) && mlbli[j] && ((ci2=linsearch(ii,mlbli[j],mlbli_n[j],nlbl))>-1))
            /*
            We found label jj[ci] in the column-list matched with nlbl in the row list.
            Since olbl was also in the row-list, this means we should just add to sum of
            differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] += pp[ci];
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else
            /* 
            So, this label has not been mixed up with nlbl before. Well, it is now.
            */
            {
               if (jj[ci] < nlbl)
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  ii[ci] = jj[ci];
                  jj[ci] = nlbl;
                  pp[ci] *= -1.0;
               }
               else
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  ii[ci] = nlbl;
               }
            }
         }
      }
      /*
      Now go through list where olbl is column index.
      */
      if (olblj)
      {
     sign2 = -1;
         for (j=0; j<olblj_n; j++)
         {
            ci = olblj[j];
        if (ii[ci] == nlbl)
            {
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            /* 
            Check if the label is currently paired up with nlbl.
            Remember that row index (ii) is always smaller than
            column index->we know where to look.
            */
            else if ((ii[ci] < nlbl) && mlblj[j] && ((ci2=linsearch(jj,mlblj[j],mlblj_n[j],nlbl))>-1))
            /*
            We found the label ii[ci] in the row-list matched with nlbl in the column list.
            Since olbl was in the column-list, this means we should just add sum of
            differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] += pp[ci]; 
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else if ((ii[ci] > nlbl) && mlblj[j] && ((ci2=linsearch(ii,mlblj[j],mlblj_n[j],nlbl))>-1))
            /*
            We found label ii[ci] in the column-list matched with nlbl in the row list.
            Since olbl was also in the column-list, this means we should sign-reverse when
            adding to sum of differences stats.
            */
            {
           if (l) {pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];}
               nn[ci2] += nn[ci];
               pp[ci2] -= pp[ci]; /* Third sign reversal. */
               k = -pp[ci2]/(2.0*PI*nn[ci2]);
               cc[ci2] = nn[ci2]*(0.5-fabs(k-floor(k+0.5)));
               nn[ci] = 0; /* Delete */
               pp[ci] = 0.0;
               cc[ci] = 0.0;
               ii[ci] = jj[ci] = INT_MAX;
               cnc--;
            }
            else
            /* 
            So, this label has not been mixed up with nlbl before. Well, it is now.
            */
            {
               if (ii[ci] < nlbl)
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  jj[ci] = nlbl;
               }
               else
               {
          if (l) 
                  {
                     pp[ci] = pp[ci] + sign1*sign2*l*2.0*PI*nn[ci];
                     k = -pp[ci]/(2.0*PI*nn[ci]);
                     cc[ci] = nn[ci]*(0.5-fabs(k-floor(k+0.5)));
                  }
                  jj[ci] = ii[ci];
                  ii[ci] = nlbl;
                  pp[ci] *= -1.0;
               }
            }
         }
      }
      if (!cnc) {break;} /* No more connections, we're done. */
      /*
      Resort index arrays ii_ia and jj_ia. Connections that are
      no longer valid have been given ii and jj values of INT_MAX,
      which means they will be out at the end of the ii_ia and jj_ia
      arrays, and will not be considered in subsequent iterations.
      */
      if ((ocnc-cnc) == 1)
      /*
      A large proportion of mergings involve merging of regions
      that have connections only with the current nlbl. Clearly
      we can do much better than a full quicksort for those cases.
      */
      {
     sillysort(ii_ia,jj_ia,ocnc);
      }
      else
      {
         qsort(ii_ia,ocnc,sizeof(int),ii_cmp);
         qsort(jj_ia,ocnc,sizeof(int),jj_cmp);
      }

      /*      return; */
   }

   mxFree(cc);
   mxFree(ii_ia);
   mxFree(jj_ia);   
   mxFree(mlbli_n);
   mxFree(mlblj_n);
   mxFree(mlbli);
   mxFree(mlblj);
   return;
}
コード例 #22
0
/* Delete item x in B-tree with root t.

	Return index:

	  SUCCESS, NOTFOUND, OR UNDERFLOW
*/
status del(btuple_t x, long t)
{
int i, j, *n, *nleft, *nright, borrowleft=0, nq;
 btuple_t *k, *ltuple, *rtuple, *item, *addr;
status code;
long *p, left, right, *lptr, *rptr, q, q1;
node nod, nod1, nod2, nodL, nodR;

 if (t == NIL)
	return(NOTFOUND);
 readnode(t, &nod);
 n = & nod.cnt;
 k = nod.tuple;
 p=nod.ptr;
 i=binsearch(x, k, *n);
 /* *t is a leaf */
 if (p[0] == NIL){
	if (i == *n || strcmp(x.index,k[i].index) < 0)
		 return NOTFOUND;
	 /* x is now equal to k[i], located in a leaf:  */
	 for (j=i+1; j < *n; j++){
		 k[j-1] = k[j];
		 p[j] = p[j+1];
	 }
	 --*n;
	writenode(t, &nod);
	 return(*n >= (t==root ? 1 : M) ? SUCCESS : UNDERFLOW);
  }
  /*  t is an interior node (not a leaf): */
  item = k+i;
  left = p[i];
  readnode(left, &nod1);
  nleft = & nod1.cnt;
    /* x found in interior node.  Go to left child *p[i] and then follow a

	  path all the way to a leaf, using rightmost branches:  */
  if (i < *n && strcmp(x.index,item->index) == 0){
	  q = p[i];
	  readnode(q, &nod1);
	  nq = nod1.cnt;
	  while (q1 = nod1.ptr[nq], q1!= NIL){
			 q = q1;
			 readnode(q, &nod1);
			 nq = nod1.cnt;
	  }
	  /*  Exchange k[i] with the rightmost item in that leaf:   */
	  addr = nod1.tuple + nq -1;
	  *item = *addr;
	  *addr = x;
	  writenode(t, &nod);
	  writenode(q, &nod1);
  }

  /*  Delete x in subtree with root p[i]:  */
	code = del(x, left);
	if (code != UNDERFLOW)
		return code;
	/*  Underflow, borrow, and , if necessary, merge:  */
	if (i < *n)
		readnode(p[i+1], &nodR);
	if (i == *n || nodR.cnt == M){
	  if (i > 0){
		 readnode(p[i-1], &nodL);
		 if (i == *n || nodL.cnt > M)
			borrowleft = 1;
	  }
	}
	/* borrow from left sibling */
	if (borrowleft){
	  item = k+i-1;
		left = p[i-1];
		right = p[i];
		nod1 = nodL;
		readnode(right, &nod2);
		nleft = & nod1.cnt;
	}else{
		right = p[i+1];        /*  borrow from right sibling   */
		readnode(left, &nod1);
		nod2 = nodR;
	}
	nright = & nod2.cnt;
	ltuple = nod1.tuple;
	rtuple = nod2.tuple;
	lptr = nod1.ptr;
	rptr = nod2.ptr;
	if (borrowleft){
		rptr[*nright + 1] = rptr[*nright];
		for (j=*nright; j>0; j--){
			rtuple[j] = rtuple[j-1];
			rptr[j] = rptr[j-1];
		}
		++*nright;
		rtuple[0] = *item;
		rptr[0] = lptr[*nleft];
		*item = ltuple[*nleft - 1];
		if (--*nleft >= M){
		  writenode(t, &nod);
		  writenode(left, &nod1);
		  writenode(right, &nod2);
		  return SUCCESS;
		}
	}else
	/* borrow from right sibling */
	 if (*nright > M){
		 ltuple[M-1] = *item;
		 lptr[M] = rptr[0];
		 *item = rtuple[0];
		 ++*nleft;
		 --*nright;
		 for (j=0; j < *nright; j++){
			 rptr[j] = rptr[j+1];
			 rtuple[j] = rtuple[j+1];
		 }
		 rptr[*nright] = rptr[*nright + 1];
		 writenode(t, &nod);
		 writenode(left, &nod1);
		 writenode(right, &nod2);
		 return(SUCCESS);
	 }
	 /*  Merge   */
	 ltuple[M-1] = *item;
	 lptr[M] = rptr[0];
	 for (j=0; j<M; j++){
		ltuple[M+j] = rtuple[j];
		lptr[M+j+1] = rptr[j+1];
	 }
	 *nleft = MM;
	 freenode(right);
	 for (j=i+1; j < *n; j++){
		 k[j-1] = k[j];
		 p[j] = p[j+1];
	 }
	 --*n;
	 writenode(t, &nod);
	 writenode(left, &nod1);
	 return( *n >= (t==root ? 1 : M) ? SUCCESS : UNDERFLOW);
}
コード例 #23
0
ファイル: 3-1.c プロジェクト: sonnym/workbook-k_and_r
int main() {
  int arr[6];
  build_array(arr, 6);

  printf("%d\n", binsearch(3, arr, 6));
}
コード例 #24
0
ファイル: insertAndSort.c プロジェクト: madaan/entire-src
    if(j<0)
    {
        a[0]=e;
        return ;//first element
    }
    while((a[j]>e)&&(j>=0))
    {
        a[j+1]=a[j];
        j--;
    }
//found correct location
    a[j+1]=e;
}
int delete(int * a ,int e,int *l)
{
    int leftLocation=binsearch(a,e,*l);
    if(*l==0)
    {
        return ;
    }
    if(leftLocation==*l-1)//last element?
    {
        *l=*l-1;
        return *l;
    }
    if(leftLocation==-1)
    {
        printf("\nWrong!");
        return -1;
    }
//now loop to reach the last element in case of duplicate element
コード例 #25
0
ファイル: slantpath.c プロジェクト: astromaddie/Transit
/* \fcnfh
 Computes optical depth at a given impact parameter, note that b needs
 to be given in units of 'rad' and the result needs to be multiplied by
 the units 'rad' to be real. 
 This uses a bent path ray solution.

 @returns $\frac{tau}{units_{rad}}$ returns optical depth divided by units
                                    of 'rad'
*/
static PREC_RES
totaltau2(PREC_RES b,		/* differential impact parameter with
				   respect to maximum value */
	  PREC_RES *rad,	/* radius array */
	  PREC_RES *refr,	/* refractivity index */
	  PREC_RES *ex,		/* extinction[rad] */
	  long nrad)		/* number of radii elements */
{
  PREC_RES dt[nrad];
  PREC_RES r0a=b;
  PREC_RES r0=0;
  int i;
  const int maxiterations=50;
  int rs;

  transiterror(TERR_CRITICAL|TERR_ALLOWCONT,
	       "Tau 2??? I'm afraid  that this has not been"
	       " successfully tested yet. I'll continue but"
	       " be critical of the result\n");

  //Look for closest approach radius
  i=0;
  while(1){
    r0=b/lineinterp(r0a,rad,refr,nrad);
    if(r0==r0a)
      break;
    if(i++>maxiterations)
      transiterror(TERR_CRITICAL,
		   "Maximum iterations(%i) reached while looking for\n"
		   "r0. Convergence not reached (%.6g!=%.6g)\n"
		   ,maxiterations,r0,r0a);
    r0a=r0;
  }

  //get bin value 'rs' such that r0 is between rad[rs-1] inclusive
  //and rad[rs] exclusive.
  //If we are looking at the outmost layer, then return
  if((rs=binsearch(rad,0,nrad-1,r0))==-5)
    return 0;
  //If some other error occurred
  else if(rs<0)
    transiterror(TERR_CRITICAL,
		 "Closest approach value(%g) is outside sampled radius\n"
		 "range(%g - %g)\n"
		 ,r0,rad[0],rad[nrad-1]);
  //advance the index to point as desired. Now nrad-rs indicates the
  //number of points available for integration.
  rs++;

  //A fraction 'analiticfrac' of the integration near the closest
  //appraoach is calcualated analitically, otherwise, I get a division
  //by zero. In formula\par
  //\[
  //\tau_{\wn}(\rho)=
  //\underbrace{
  //\frac{2\extc_{\wn}\rho}{n}\left(
  //                   \sqrt{\left(\frac{nr_1}{\rho}\right)^2-1}
  //                  -\sqrt{\left(\frac{nr_0}{\rho}\right)^2-1}\right) 
  //}_{\mathrm{analitic}} +
  //\underbrace{
  //2\int_{r_1=r_0+\delta r}^{\infty}
  //\frac{\extc_{\wn}~n~r}{\sqrt{n^2r^2-\rho^2}}\dd r
  //}_{\mathrm{numerical}}
  //\]\par
  //First for the analitical part of the integral
  PREC_RES res;
  if(ex[rs-1]==ex[rs])
    res= ex[rs] * r0 * ( sqrt( rad[rs] * rad[rs] / r0 / r0 - 1) );
  else{
    PREC_RES alpha = ( ex[rs] - ex[rs-1] ) / ( rad[rs] - rad[rs-1] );
    PREC_RES rm    = rad[rs];
    if(alpha<0)
      res= - alpha * (rm * sqrt( rm * rm - r0 * r0) - r0 * r0 * 
		      log( sqrt( rm * rm / r0 / r0 - 1) + rm / r0 ) )
	/ 2.0;
    else
      res=   alpha * (rm * sqrt( rm * rm - r0 * r0) + r0 * r0 * 
		      log( sqrt( rm * rm / r0 / r0 - 1) + rm / r0 ) )
	/ 2.0;
  }

  //And now for the numerical integration. Set the variables
  for(i=rs;i<nrad;i++){
    r0a=b/refr[i]/rad[i];
    transitASSERT(r0a>1,
		  "Oops! condition could not be asserted, b/(nr)=%g > 1\n"
		  ,r0a);

    dt[i]=ex[i]/sqrt(1-r0a*r0a);
  }

  //Integrate!\par
  //Use spline if GSL is available along with at least 3 points
#ifdef _USE_GSL
  if(nrad-rs>2){
    gsl_interp_accel *acc = gsl_interp_accel_alloc ();
    gsl_spline *spl=gsl_spline_alloc(gsl_interp_cspline,nrad-rs);
    gsl_spline_init(spl,rad+rs,dt+rs,nrad-rs);
    res+=gsl_spline_eval_integ(spl,rad[rs],rad[nrad-1],acc);
    gsl_spline_free(spl);
    gsl_interp_accel_free (acc);
  }
  //Only integrate Trapezium if there are only two points available.
  else
#endif /* _USE_GSL */
  //Integrate Simpson-Trapezium if enough(w/o GSL) or not enough(w/ GSL)
  //elements. 
  if(nrad-rs>1)
    res+=integ_trasim(rad[1]-rad[0],dt+rs,nrad-rs);

  return 2*(res);
}
コード例 #26
0
ファイル: moglcore.c プロジェクト: Epixoft/Psychtoolbox-3
/* This is the main entry point for Matlab or Octave. It gets called by
   Matlab or Octave, handles first-time initialization, error handling
   and subfunction dispatching.
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    // Start of dispatcher:
    int i;
    GLenum err;
    
    // FreeGlut must be initialized, otherwise it will emergency abort the whole application.
    // These variables are needed for it:
    int noargs = 1;
    char dummyarg[] = "ptbmoglcore";
    char *dummyargp = &dummyarg[0];

    // see whether there's a string command
    if(nrhs<1 || !mxIsChar(prhs[0])) mogl_usageerr();
    
    // get string command
    mxGetString(prhs[0],cmd,CMDLEN);

    // Special case. If we're called with the special command "PREINIT", then
    // we return immediately. moglcore('PREINIT') is called by ptbmoglinit.m
    // on M$-Windows in order to preload the moglcore Mex-file into Matlab while
    // the current working directory is set to ..MOGL/core/ . This way, the dynamic
    // linker can find our own local version of glut32.dll and link it against moglcore.
    // Without this trick, we would need to install glut32.dll into the Windows system
    // folder which requires admin privileges and makes installation of Psychtoolbox
    // more complicated on M$-Windows...
    if (strcmp(cmd, "PREINIT")==0) {
        glBeginLevel=0;
        goto moglreturn;
    }
    
    if (strcmp(cmd, "DUMMYMODE")==0) {
        if (nrhs<2 || mxGetScalar(prhs[1])<0) {
            mexErrMsgTxt("MOGL-ERROR: No dummy mode level or invalid level (<0) given for subcommand DUMMYMODE!");
        }
        dummymode = (int) mxGetScalar(prhs[1]);
	if (dummymode>0) printf("MOGL-INFO: Switched to dummy mode level %i.\n", dummymode);
        goto moglreturn;
    }

    // Special command to set MOGL debug level:
    // debuglevel = 0 --> Shut up in any case, leave error-handling to higher-level code.
    // debuglevel > 0 --> Check for OpenGL error conditions.
    // debuglevel > 0 --> Output glError()'s in clear-text and abort. Output GLSL errors and abort.
    // debuglevel > 1 --> Output GLSL diagnostic messages as well.
    // debuglevel > 2 --> Be very verbose!
    if (strcmp(cmd, "DEBUGLEVEL")==0) {
        if (nrhs<2 || mxGetScalar(prhs[1])<0) {
            mexErrMsgTxt("MOGL-ERROR: No debuglevel or invalid debuglevel (<0) given for subcommand DEBUGLEVEL!");
        }

        debuglevel = (int) mxGetScalar(prhs[1]);
        goto moglreturn;
    }
    
    // Special cleanup subcommand needed for GNU/Octave: See explanation below in firstTime init.
    if (strcmp(cmd, "JettisonModuleHelper")==0) {
      goto moglreturn;
    }

    // Abort here if dummymode >= 10: Input arg. processing run, but no real
    // command parsing and processing;
    if (dummymode >= 10) {
      printf("MOGL-INFO: Dummy call to %s() - Ignored in dummy mode %i ...\n", cmd, dummymode);
      goto moglreturn;
    }

    #ifdef BUILD_GLM
    // GLM module is included and supported in moglcore: This is necessary if
    // one wants to use MOGL independent from Psychtoolbox. GLM is only supported
    // on MacOS-X, not on Linux or Windows...
    
    // We execute glm-commands without performing GLEW first-time initialization,
    // because to execute glewinit() we need a valid OpenGL context. This context is
    // either created by Psychtoolbox or by glm. Therefore glm-commands must be able
    // to execute before glewinit() happened.
    
    // look for command in glm command map
    if( (i=binsearch(glm_map,glm_map_count,cmd))>=0 ) {
        glm_map[i].cmdfn(nlhs,plhs,nrhs-1,prhs+1);
        goto moglreturn;
    }

    #endif

    // Is this the first invocation of moglcore?
    if (firsttime) {
        // Yes. Initialize GLEW, the GL Extension Wrangler Library. This will
        // auto-detect and dynamically link/bind all core OpenGL functionality
        // as well as all possible OpenGL extensions on OS-X, Linux and Windows.
        err = GLEW_OK;
        #ifdef PTB_USE_WAFFLE
        // Linux is special: If we use the Waffle backend for display system binding, then our display backend
        // may be something else than GLX (e.g., X11/EGL, Wayland/EGL, GBM/EGL, ANDROID/EGL etc.), in which case
        // glewInit() would not work and would crash hard. Detect if we're on classic Linux or Linux with X11/GLX.
        // If so, execute glewInit(), otherwise call glewContextInit() - a routine which skips GLX specific setup,
        // therefore only initializes the non-GLX parts. We need a hacked glew.c for this function to be available,
        // as original upstream GLEW makes that function private (static):
        if (!getenv("PSYCH_USE_DISPLAY_BACKEND") || strstr(getenv("PSYCH_USE_DISPLAY_BACKEND"), "glx")) {
            // Classic backend or GLX backend: The full show.
            err = glewInit();
        }
        else {
            // Non-GLX backend, probably EGL: Reduced show.
            err = glewContextInit();
        }
        #else
            // Other os'es, or Linux without Waffle backend: Always init GLEW:
            err = glewInit();
        #endif

        if (GLEW_OK != err) {
            // Failed! Something is seriously wrong - We have to abort :(
            printf("MOGL: Failed to initialize! Probably you called an OpenGL command *before* opening an onscreen window?!?\n");
            printf("GLEW reported the following error: %s\n", glewGetErrorString(err)); fflush(NULL);
            goto moglreturn;
        }

        // Success. Ready to go...
		if (debuglevel > 1) {
			printf("MOGL - OpenGL for Matlab & GNU/Octave initialized. MOGL is (c) 2006-2013 Richard F. Murray & Mario Kleiner, licensed to you under MIT license.\n");
            #ifdef WINDOWS
			printf("On MS-Windows, we make use of the freeglut library, which is Copyright (c) 1999-2000 Pawel W. Olszta, licensed under compatible MIT/X11 license.\n");
            printf("The precompiled Windows binary DLL's have been kindly provided by http://www.transmissionzero.co.uk/software/freeglut-devel/ -- Thanks!\n");
            #endif
			printf("See file 'License.txt' in the Psychtoolbox root folder for the exact licensing conditions.\n");
		}
        fflush(NULL);
        
        // Perform dynamic rebinding of ARB extensions to core functions, if necessary:
        mogl_rebindARBExtensionsToCore();
        
		#ifdef FREEGLUT
		// FreeGlut must be initialized, otherwise it will emergency abort the whole application.
		// However, we skip init if we're on a setup without GLX display backend, as this would
		// abort us due to lack of GLX. On non-GLX we simply can't use FreeGlut at all.
		if (!getenv("PSYCH_USE_DISPLAY_BACKEND") || strstr(getenv("PSYCH_USE_DISPLAY_BACKEND"), "glx")) {
			// GLX display backend - Init and use FreeGlut:
			glutInit( &noargs, &dummyargp);
		}
		#endif

        // Running on a OpenGL-ES rendering api under Linux?
        if (getenv("PSYCH_USE_GFX_BACKEND") && strstr(getenv("PSYCH_USE_GFX_BACKEND"), "gles")) {
            // Yes. We emulate some immediate mode rendering commands, which aren't available
            // in OpenGL Embedded Subset at all, via "our" own emulation code. This code emulates
            // immediate mode on top of client vertex arrays and batch submission.
            if (debuglevel > 1) {
                printf("OpenGL-ES rendering API active: Emulating immediate mode rendering via David Petrie's ftglesGlue emulation code.\n");
            }
        }

		// Register exit-handler: When flushing the mex-file, we free all allocated buffer memory:
		mexAtExit(&mexExitFunction);
		
        // Done with first time initialization:
        firsttime = 0;
    }   
	
    // If glBeginLevel >  1 then most probably the script was aborted after execution of glBegin() but
    // before execution of glEnd(). In that case, we reset the level to zero.
    if (glBeginLevel > 1) glBeginLevel = 0;

    // Reset OpenGL error state so we can be sure that any of our error queries really
    // relate to errors caused by us:
    if (glBeginLevel == 0 && debuglevel > 0 && (strstr(cmd, "glGetError")==NULL)) glGetError();
        
    // look for command in manual command map
    if( (i=binsearch(gl_manual_map,gl_manual_map_count,cmd))>=0 ) {
        gl_manual_map[i].cmdfn(nlhs,plhs,nrhs-1,(const mxArray**) prhs+1);
        if (debuglevel > 0) mogl_checkerrors(cmd, prhs);
        goto moglreturn;
    }
    
    // look for command in auto command map
    if( (i=binsearch(gl_auto_map,gl_auto_map_count,cmd))>=0 ) {
        gl_auto_map[i].cmdfn(nlhs,plhs,nrhs-1,(const mxArray**) prhs+1);
        if (debuglevel > 0) mogl_checkerrors(cmd, prhs);
        goto moglreturn;
    }
    
    // no match
    mogl_usageerr();
    
    // moglreturn: Is the exit path of mogl. All execution ends at this point.
 moglreturn:
    return;
}
コード例 #27
0
//___________________________________________________________________________________
void mexFunction(int nOUT, mxArray *pOUT[],
                 int nINP, const mxArray *pINP[])
{

    int i;
    double *records_to_get, *range_to_get,*t,*wv, *all_timestamps;
    int n_records_to_get = 0;
    int record_units = 0;
    int nSpikesInFile = 0;
    int length_records_to_get = 0;
    int start_idx=0;
    int end_idx = 0;
    int idx = 0;
    /* check number of arguments: expects 1 input */
    if (nINP != 3 && nINP != 1)
        mexErrMsgTxt("Call with fn or fn and array of recs to load(vector), and 1(timestamp) or 2(record number	) as inputs.");
    if (nOUT > 2)
        mexErrMsgTxt("Requires two outputs (t, wv).");

    /* read inputs */
    int fnlen = (mxGetM(pINP[0]) * mxGetN(pINP[0])) + 1;
    char *fn = (char *) mxCalloc(fnlen, sizeof(char));
    if (!fn)
        mexErrMsgTxt("Not enough heap space to hold converted string.");
    int errorstatus = mxGetString(pINP[0], fn,fnlen);
    if (errorstatus)
        mexErrMsgTxt("Could not convert string data.");


    nSpikesInFile = GetNumberOfSpikes(fn);
    ////////////////////////////////////////////////////////
    // If only one input is passed, assume the whole file is
    // to be loaded. If only one output is present, assume it is
    // only timestamps.
    ////////////////////////////////////////////////////////

    if(nINP == 1 && nOUT == 1)
    {
        /* Return the timestamps of all of the records */
        // create outputs
        pOUT[0] = mxCreateDoubleMatrix(nSpikesInFile, 1, mxREAL);
        t = mxGetPr(pOUT[0]);

        // load tt file fn into t and wv arrays
        ReadTT_timestamps(fn,nSpikesInFile,t);

        // cleanup
        mxFree(fn);
        return;

    } else if(nINP == 1 && nOUT == 2)
    {
        ////////////////////////////////////////////////////////
        // create outputs
        ////////////////////////////////////////////////////////
        mexPrintf("Getting %i records.\n",nSpikesInFile);
        pOUT[0] = mxCreateDoubleMatrix(nSpikesInFile , 1, mxREAL);
        t = mxGetPr(pOUT[0]);
        int wvDims[] = {nSpikesInFile , 4, 32};    // wv = nSpikes x 4 x 32   FORTRAN (column major) array
        pOUT[1] = mxCreateNumericArray(3, wvDims, mxDOUBLE_CLASS, mxREAL);
        wv = mxGetPr(pOUT[1]);

        ////////////////////////////////////////////////////////
        // load tt file fn into t and wv arrays
        ////////////////////////////////////////////////////////

        ReadTT(fn,nSpikesInFile ,t,wv);

        ////////////////////////////////////////////////////////
        // cleanup
        ////////////////////////////////////////////////////////

        mxFree(fn);
        return;
    }
    ////////////////////////////////////////////////////////
    // unpack inputs
    ////////////////////////////////////////////////////////
    length_records_to_get = mxGetM(pINP[1]) * mxGetN(pINP[1]);
    records_to_get = mxGetPr(pINP[1]);
    record_units = (int) mxGetScalar(pINP[2]);

    switch(record_units)
    {
    case BY_TIMESTAMP:
        ////////////////////////////////////////////////////////
        // Convert the timestamps into record numbers. This will
        // make loading these records easy.
        ////////////////////////////////////////////////////////
        ////////////////////////////////////////////////////////
        // Create a very large array of all of the timestamps
        ////////////////////////////////////////////////////////
        n_records_to_get = length_records_to_get;
        all_timestamps = (double *)calloc( nSpikesInFile, sizeof( double ) );
        if (all_timestamps == NULL)
            mexErrMsgTxt("NOT ENOUGH MEMORY");
        range_to_get = (double *) calloc( n_records_to_get, sizeof( double ) );
        if (range_to_get == NULL)
            mexErrMsgTxt("NOT ENOUGH MEMORY");

        ReadTT_timestamps(fn,nSpikesInFile,all_timestamps);

        for (i = 0; i<n_records_to_get; i++)
        {
            idx = binsearch(nSpikesInFile, all_timestamps, &records_to_get[i]);
            range_to_get[i] = idx + 1; // Add one since records are assumed
            // to be from 1 to end.
        }

        free(all_timestamps);
        break;

    case BY_RECORD:
        ////////////////////////////////////////////////////////
        // Get records asked for. First, subract one since matlab
        // users typically think records as being ordered from
        // 1 to ....
        ////////////////////////////////////////////////////////

        n_records_to_get = length_records_to_get;
        range_to_get = records_to_get;
        break;

    case BY_TIMESTAMP_RANGE:

        ////////////////////////////////////////////////////////
        // Error checking
        ////////////////////////////////////////////////////////

        if(length_records_to_get != 2)
        {
            mexErrMsgTxt("Must pass in two arguements for parameter 2.");
            return;
        }

        ////////////////////////////////////////////////////////
        // Create a very large array of all of the timestamps
        ////////////////////////////////////////////////////////
        all_timestamps = (double *)calloc( nSpikesInFile, sizeof( double ) );
        if (all_timestamps == NULL)
            mexErrMsgTxt("NOT ENOUGH MEMORY");

        ReadTT_timestamps(fn,nSpikesInFile,all_timestamps);
        ////////////////////////////////////////////////////////
        // Find the index in all_timestamps of the start record.
        ////////////////////////////////////////////////////////

        start_idx = binsearch(nSpikesInFile, all_timestamps, &records_to_get[0]) + 1; // Add one since records are assumed
        // to be from 1 to end.

        ////////////////////////////////////////////////////////
        // Find the index in all_timestamps of the end record.
        ////////////////////////////////////////////////////////
        end_idx = binsearch(nSpikesInFile, all_timestamps, &records_to_get[1]) + 1;  // Add one since records are assumed
        // to be from 1 to end.


        free(all_timestamps);

        n_records_to_get = end_idx - start_idx + 1;
        ////////////////////////////////////////////////////////
        // Allocate the space
        // Using ints would be much more efficient, but it would make it necessary
        // to rewrite the ReadTT program. I don't want to do that.
        ////////////////////////////////////////////////////////

        range_to_get = (double *) calloc( n_records_to_get, sizeof( double ) );
        if (range_to_get == NULL)
        {
            mexErrMsgTxt("NOT ENOUGH MEMORY");
            return;
        }

        for (i = 0; i<n_records_to_get; i++)
            range_to_get[i] = start_idx + i;

        break;

    case BY_RECORD_RANGE:
        ////////////////////////////////////////////////////////
        // This is easy. First check to make sure the user passed in
        // the proper number of arguements.
        ////////////////////////////////////////////////////////
        if(length_records_to_get != 2)
        {
            mexErrMsgTxt("Must pass in a start and end record number for argument 2.");
            return;
        }
        start_idx = (int) records_to_get[0] ;
        end_idx   = (int) records_to_get[1] ;

        ////////////////////////////////////////////////////////
        n_records_to_get = end_idx - start_idx + 1;
        ////////////////////////////////////////////////////////
        // Allocate the space
        ////////////////////////////////////////////////////////
        range_to_get = (double  *)calloc( n_records_to_get, sizeof( double  ) );
        if (range_to_get == NULL)
        {
            mexErrMsgTxt("NOT ENOUGH MEMORY");
            return;
        }
        for (i = 0; i<n_records_to_get; i++)
        {
            range_to_get[i] = start_idx + i;
        }
        break;

    case COUNTSPIKES: // ADR/NCST
        printf("Counting spikes.\n");
        pOUT[0] = mxCreateDoubleMatrix(1,1,mxREAL);
        t = mxGetPr(pOUT[0]);
        t[0] = nSpikesInFile;
        break;

    default:
        mexErrMsgTxt("Incorrect parameter 3.");
    }
    if (!(record_units==COUNTSPIKES))
    {
        ////////////////////////////////////////////////////////
        // Allocate the space
        ////////////////////////////////////////////////////////
        printf("Getting %i records.\n",n_records_to_get);
        pOUT[0] = mxCreateDoubleMatrix(n_records_to_get, 1, mxREAL);
        t = mxGetPr(pOUT[0]);
        int wvDims[] = {n_records_to_get, 4, 32};    // wv = nSpikes x 4 x 32   FORTRAN (column major) array
        pOUT[1] = mxCreateNumericArray(3, wvDims, mxDOUBLE_CLASS, mxREAL);
        wv = mxGetPr(pOUT[1]);
        ////////////////////////////////////////////////////////
        // Get the data. Record_units will whether to get by
        // timestamp or by record number.
        ////////////////////////////////////////////////////////
        ReadTTByRecord(fn,range_to_get,n_records_to_get,t,wv);

        // Free this variable only if it was not a matlab variable.
        if (record_units == BY_TIMESTAMP_RANGE || record_units == BY_RECORD_RANGE )
            free(range_to_get);
    }
    // cleanup
    mxFree(fn);

}
コード例 #28
0
ファイル: tree.c プロジェクト: Kotty666/xymon
xtreeStatus_t xtreeAdd(void *treehandle, char *key, void *userdata)
{
	xtree_t *mytree = (xtree_t *)treehandle;
	xtreePos_t n;

	if (treehandle == NULL) return XTREE_STATUS_NOTREE;

	if (mytree->treesz == 0) {
		/* Empty tree, just add record */
		mytree->entries = (treerec_t *)calloc(1, sizeof(treerec_t));
		mytree->entries[0].key = key;
		mytree->entries[0].userdata = userdata;
		mytree->entries[0].deleted = 0;
	}
	else {
		n = binsearch(mytree, key);

		if ((n >= 0) && (n < mytree->treesz) && (mytree->compare(key, mytree->entries[n].key) == 0)) {
			/* Record already exists */

			if (mytree->entries[n].deleted != 0) {
				/* Revive the old record. Note that we can now discard our privately held key */
				free(mytree->entries[n].key);

				mytree->entries[n].key = key;
				mytree->entries[n].deleted = 0;
				mytree->entries[n].userdata = userdata;
				return XTREE_STATUS_OK;
			}
			else {
				/* Error */
				return XTREE_STATUS_DUPLICATE_KEY;
			}
		}

		/* Must create new record */
		if (mytree->compare(key, mytree->entries[mytree->treesz - 1].key) > 0) {
			/* Add after all the others */
			mytree->entries = (treerec_t *)realloc(mytree->entries, (1 + mytree->treesz)*sizeof(treerec_t));
			mytree->entries[mytree->treesz].key = key;
			mytree->entries[mytree->treesz].userdata = userdata;
			mytree->entries[mytree->treesz].deleted = 0;
		}
		else if (mytree->compare(key, mytree->entries[0].key) < 0) {
			/* Add before all the others */
			treerec_t *newents = (treerec_t *)malloc((1 + mytree->treesz)*sizeof(treerec_t));
			newents[0].key = key;
			newents[0].userdata = userdata;
			newents[0].deleted = 0;
			memcpy(&(newents[1]), &(mytree->entries[0]), (mytree->treesz * sizeof(treerec_t)));
			free(mytree->entries);
			mytree->entries = newents;
		}
		else {
			treerec_t *newents;

			n = binsearch(mytree, key);
			if (mytree->compare(mytree->entries[n].key, key) < 0) n++;

			/* 
			 * n now points to the record AFTER where we will insert data in the current list.
			 * So in the new list, the new record will be in position n.
			 * Check if this is a deleted record, if it is then we won't have to move anything.
			 */
			if (mytree->entries[n].deleted != 0) {
				/* Deleted record, let's re-use it. */
				free(mytree->entries[n].key);
				mytree->entries[n].key = key;
				mytree->entries[n].userdata = userdata;
				mytree->entries[n].deleted = 0;
				return XTREE_STATUS_OK;
			}

			/* Ok, must create a new list and copy entries there */
			newents = (treerec_t *)malloc((1 + mytree->treesz)*sizeof(treerec_t));

			/* Copy record 0..(n-1), i.e. n records */
			memcpy(&(newents[0]), &(mytree->entries[0]), n*sizeof(treerec_t));

			/* New record is the n'th record */
			newents[n].key = key;
			newents[n].userdata = userdata;
			newents[n].deleted = 0;

			/* Finally, copy records n..(treesz-1) from the old list to position (n+1) onwards in the new list */
			memcpy(&(newents[n+1]), &(mytree->entries[n]), (mytree->treesz - n)*sizeof(treerec_t));

			free(mytree->entries);
			mytree->entries = newents;
		}
	}

	mytree->treesz += 1;
	return XTREE_STATUS_OK;
}
コード例 #29
0
ファイル: commands.c プロジェクト: jalishah/airborne
int in_command_exists(int value)
{
   int ret = binsearch(value, commands_in,
                       sizeof(commands_in) / sizeof(int));
   return ret != -1;
}
コード例 #30
0
ファイル: 6.4.c プロジェクト: mScotty/the_labyrinth
/* isnoiseword: wrapper for searchnoise, returns 1 if word is noise, else 0 */
int noiseword(char *word)
{
    return binsearch(word, noise, NKEYS) < 0 ? 0 : 1;
}