Beispiel #1
0
void test_search_element_from_the_list_of_Strings_which_is_not_available() {
    String elements[3] = {"shabrin","shital","manali"};
    String key = "shay";
    String* result = binarySearch(elements,&key, 3, sizeof(String), compareString);
    ASSERT(NULL == (String*)result);
};
Beispiel #2
0
int32_t CharsetRecog_mbcs::match_mbcs(InputText *det, const uint16_t commonChars[], int32_t commonCharsLen) const {
    int32_t singleByteCharCount = 0;
    int32_t doubleByteCharCount = 0;
    int32_t commonCharCount     = 0;
    int32_t badCharCount        = 0;
    int32_t totalCharCount      = 0;
    int32_t confidence          = 0;
    IteratedChar iter;

    while (nextChar(&iter, det)) {
        totalCharCount++;

        if (iter.error) {
            badCharCount++;
        } else {
            if (iter.charValue <= 0xFF) {
                singleByteCharCount++;
            } else {
                doubleByteCharCount++;

                if (commonChars != 0) {
                    if (binarySearch(commonChars, commonCharsLen, static_cast<uint16_t>(iter.charValue)) >= 0){
                        commonCharCount += 1;
                    }
                }
            }
        }


        if (badCharCount >= 2 && badCharCount*5 >= doubleByteCharCount) {
            // Bail out early if the byte data is not matching the encoding scheme.
            // break detectBlock;
            return confidence;
        }
    }

    if (doubleByteCharCount <= 10 && badCharCount == 0) {
        // Not many multi-byte chars.
        if (doubleByteCharCount == 0 && totalCharCount < 10) {
            // There weren't any multibyte sequences, and there was a low density of non-ASCII single bytes.
            // We don't have enough data to have any confidence.
            // Statistical analysis of single byte non-ASCII charcters would probably help here.
            confidence = 0;
        }
        else {
            //   ASCII or ISO file?  It's probably not our encoding,
            //   but is not incompatible with our encoding, so don't give it a zero.
            confidence = 10;
        }

        return confidence;
    }

    //
    //  No match if there are too many characters that don't fit the encoding scheme.
    //    (should we have zero tolerance for these?)
    //
    if (doubleByteCharCount < 20*badCharCount) {
        confidence = 0;

        return confidence;
    }

    if (commonChars == 0) {
        // We have no statistics on frequently occuring characters.
        //  Assess confidence purely on having a reasonable number of
        //  multi-byte characters (the more the better)
        confidence = 30 + doubleByteCharCount - 20*badCharCount;

        if (confidence > 100) {
            confidence = 100;
        }
    } else {
        //
        // Frequency of occurence statistics exist.
        //

        double maxVal = log((double)doubleByteCharCount / 4); /*(float)?*/
        double scaleFactor = 90.0 / maxVal;
        confidence = (int32_t)(log((double)commonCharCount+1) * scaleFactor + 10.0);

        confidence = min(confidence, 100);
    }

    if (confidence < 0) {
        confidence = 0;
    }

    return confidence;
}
Beispiel #3
0
//#############################################################################
void 
MibSBilevel::createBilevel(CoinPackedVector* sol, 
			   MibSModel *mibs)
{
  
  /** Splits sol into two parts, upper- and lower-level components **/

  if(!mibs) return;
  
  model_ = mibs;

  heuristic_ = new MibSHeuristic(mibs);
  
  int i(0);
  int N(model_->numVars_);
  int lN(model_->lowerDim_); // lower-level dimension
  //int uN(N - lN); // upper-level dimension
  int uN(model_->upperDim_); // upper-level dimension
  double etol(model_->BlisPar()->entry(BlisParams::integerTol));
  //double etol(model_->etol_); 
  
  assert(N == model_->solver()->getNumCols());
  
  int *indices = sol->getIndices();
  double *values = sol->getElements();
  int numElements(sol->getNumElements()); // number of nonzero elements
  
  //FIXME: These don't seem to be used anymore. 
  if(!lowerSolution_)
    lowerSolution_ = new double[lN];
  if(!upperSolution_)
    upperSolution_ = new double[uN];
  CoinZeroN(lowerSolution_, lN);
  CoinZeroN(upperSolution_, uN);

  if(!lowerSolutionOrd_)
    lowerSolutionOrd_ = new double[lN];
  if(!upperSolutionOrd_)
    upperSolutionOrd_ = new double[uN];
  CoinZeroN(lowerSolutionOrd_, lN);
  CoinZeroN(upperSolutionOrd_, uN);
  
  isIntegral_ = true;
  isUpperIntegral_ = true;
  isBilevelFeasible_ = true;
  
  int * lowerColInd = mibs->getLowerColInd();
  int * upperColInd = mibs->getUpperColInd();
  int index(0), uCount(0), lCount(0);
  
  /*
  for(i = 0; i < numElements; i ++){
    index = indices[i];
    if(binarySearch(0, lN - 1, index, lowerColInd) < 0){
      if(fabs(floor(values[i] + 0.5) - values[i]) > etol){
	isIntegral_ = false;
	isBilevelFeasible_ = false;
	upperSolution_[uCount++] = values[i];
      }
      else{
	upperSolution_[uCount++] = floor(values[i] + 0.5);
      }
    }
    else{
      if(fabs(floor(values[i] + 0.5) - values[i]) > etol){
	isIntegral_ = false;
	isBilevelFeasible_ = false;
	lowerSolution_[lCount++] = values[i];
      }    
      else{
	lowerSolution_[lCount++] = floor(values[i] + 0.5);
      }
    }
  }
  */

  //changed this 5/12 to allow for continuous variables

  //FIXME: THIS IS WRONG.  
  //VALUES SHOULD EITHER BE PLACED DIFFERENTLY OR VECTORS MADE SMALLER
  //PROBABLY PLACE THEM DIFFERENTLY AS BELOW, KEEPING NONZERO PLACES
  /*
  for(i = 0; i < numElements; i ++){
    index = indices[i];
    if(binarySearch(0, lN - 1, index, lowerColInd) < 0){
       if(fabs(floor(values[i] + 0.5) - values[i]) > etol){
	  if(mibs->solver()->isInteger(i)){
	     isIntegral_ = false;
	     isBilevelFeasible_ = false;
	  }
	  upperSolution_[uCount++] = values[i];	     
       }
       else{
	  if(mibs->solver()->isInteger(i))
	     upperSolution_[uCount++] = floor(values[i] + 0.5);
	  else
	     upperSolution_[uCount++] = values[i];
       }
    }
    else{
       if(fabs(floor(values[i] + 0.5) - values[i]) > etol){
	  if(mibs->solver()->isInteger(i)){
	     isIntegral_ = false;
	     isBilevelFeasible_ = false;
	  }
	  lowerSolution_[lCount++] = values[i];
       }    
       else{
	  if(mibs->solver()->isInteger(i))
	     lowerSolution_[lCount++] = floor(values[i] + 0.5);
	  else
	     lowerSolution_[lCount++] = values[i];
       }
    }
  }
  */

  const double *lower = model_->solver()->getColLower();
  const double *upper = model_->solver()->getColUpper();
  double value;
  for(i = 0; i < numElements; i ++){
    index = indices[i];
    value = CoinMax(values[i], lower[index]);
    value = CoinMin(value, upper[index]);
    if(binarySearch(0, uN - 1, index, upperColInd) >= 0){
       if(fabs(floor(value + 0.5) - value) > etol){
#if 1
	  //This check is failing when Blis has already declared the solution integral
	  //It's not really needed
	  if(mibs->solver()->isInteger(index)){
	     isUpperIntegral_ = false;
	     isIntegral_ = false;
	     isBilevelFeasible_ = false;
	  }
#endif
       }
    }
    else{
       if(fabs(floor(value + 0.5) - value) > etol){
#if 1
	  //This check is failing when Blis has already declared the solution integral
	  //It's not really needed
	  if(mibs->solver()->isInteger(index)){
	     isIntegral_ = false;
	     isBilevelFeasible_ = false;
	  }
#endif
       }    
    }
  }
 

  /* put the solution in order by integers first */

  int pos(0);

  for(i = 0; i < numElements; i ++){
    index = indices[i];
    pos = binarySearch(0, lN - 1, index, lowerColInd);
    if(pos < 0){
      pos = binarySearch(0, uN - 1, index, upperColInd);
      upperSolutionOrd_[pos] = values[i];
    }
    else
      lowerSolutionOrd_[pos] = values[i];
  }

  if(isUpperIntegral_)
     checkBilevelFeasiblity(mibs->isRoot_);

}
int  calculateNoOfPoints(int *x,int *y,int i,int j,int n)
{
    float x3,y3,x4,y4;
    int a,b,c,d,counter,x5,y5,x6,y6,x7,y7,x8,y8,k,counter1,counter2,max,temp,flag,index;
    long long int distanceSquare,dis1,dis2;
    a=x[i];
    b=y[i];
    c=x[j];
    d=y[j];

    x3=(a-b+c+d)/2.0 ;
    y3=(a+b-c+d)/2.0 ;
    x4=(a+b+c-d)/2.0 ;
    y4=(-a+b+c+d)/2.0 ;

    x5=d-b+a;
    y5=a-c+b;
    x6=b-d+a;
    y6=c-a+b;
    x7=b-d+c;
    y7=c-a+d;
    x8=d-b+c;
    y8=a-c+d;

    distanceSquare=calculateSquareDistance(x[i],y[i],x[j],y[j]);
    dis1=calculateSquareDistance(x5,y5,x7,y7);
    dis2=calculateSquareDistance(x5,y5,x8,y8);

    if(dis1!=distanceSquare)
    {
        temp=x7;
        x7=x8;
        x8=temp;

        temp=y7;
        y7=y8;
        y8=temp;
    }

    counter=counter1=counter2=0;
    flag=0;
    if(isInteger(x3) && isInteger(y3) && isInteger(x4) && isInteger(y4))
        flag=1;

    if(flag==1)
    {
        if((index=binarySearch(x,n,(int)x3))!=-1 && y[index]==(int)y3)
            counter++;
        if((index=binarySearch(x,n,(int)x4))!=-1 && y[index]==(int)y4)
            counter++;
        if(counter==2)
            return 0;

        if((index=binarySearch(x,n,(int)x5))!=-1 && y[index]==(int)y5)
            counter1++;
        if((index=binarySearch(x,n,(int)x7))!=-1 && y[index]==(int)y7)
            counter1++;
        if(counter1==2)
            return 0;

        if((index=binarySearch(x,n,(int)x6)!=-1) && y[index]==(int)y6)
            counter2++;
        if((index=binarySearch(x,n,(int)x8)!=-1) && y[index]==(int)y8)
            counter2++;
        if(counter2==2)
            return 0;

    }
    else
    {
        if((index=binarySearch(x,n,(int)x5))!=-1 && y[index]==(int)y5)
            counter1++;
        if((index=binarySearch(x,n,(int)x7))!=-1 && y[index]==(int)y7)
            counter1++;
        if(counter1==2)
            return 0;

        if((index=binarySearch(x,n,(int)x6)!=-1) && y[index]==(int)y6)
            counter2++;
        if((index=binarySearch(x,n,(int)x8)!=-1) && y[index]==(int)y8)
            counter2++;
        if(counter2==2)
            return 0;
    }

    max=(counter>=counter1)?(counter>=counter2?counter:counter2):(counter1>=counter2?counter1:counter2);
    if(max==0)
        return 2;
    return 1;
}
/*
  This function produces a graphviz file of the graph passed to it,
  but it colors the nodes based on the colors provided in color and
  sizes the nodes based on the node size parameter.  To prevent the
  files from getting out of hand, we make the largest bag 1.1 and the
  smallest bag 0.1.
 */
void write_scaled_square_graphviz(Graph & G, string output_file, vector<double> color, vector<size_t> sizes, vector<int> square_nodes, bool directed)
{
  ofstream output;
  output.open(output_file.c_str());

  double color_min = color[0];
  double color_max = color[0];
  size_t size_min = sizes[0];
  size_t size_max = sizes[0];
 
  v_size_t n = num_vertices(G);
  vector<double> node_weight(n, 0);

  if (color.size() != sizes.size() || color.size() != n)
    {
      cout<<"Color vector, size vector must all be of length num_nodes in graph. Exiting. \n";
      exit(EXIT_FAILURE);
    }

  for (size_t i = 0; i < color.size(); ++i)
    {
      if(color[i] > color_max)
	color_max = color[i];

      if(color[i] < color_min)
	color_min = color[i];

      if(sizes[i] > size_max)
	size_max = sizes[i];

      if(sizes[i] < size_min)
	size_min = sizes[i];
    }

  if (color_max > 1 or color_min < 0)
    {
      cout<<"Color vector must be in range [0,1]. Exiting.\n";
      exit(EXIT_FAILURE);
    }

  output<<"Graph color {\n";
  output<<"splines=false;\n";

  graph_traits<Graph>::edge_iterator eit, eitend;
  graph_traits<Graph>::vertex_iterator vit, vitend;

  property_map<Graph, vertex_index_t>::type index = get(vertex_index,G);

  for (tie(vit,vitend) = vertices(G); vit != vitend; ++vit)
    {
      Vert      v = *vit;
      v_size_t vi = index[v];
      char rgb[8];
      double width = .75;
      if (size_max != size_min)
	width = 0.1 + ((double) sizes[vi] - size_min) / (double) (size_max - size_min);
      
      double val = 0.5;
      node_weight[vi] = 1.0 / width;

      val = color[vi];
      
      get_rgb_value(rgb, val);

      int found = binarySearch(square_nodes,vi);
      
      if (found == -1)
	output<<vi<<"[label=\"\", width="<<width<<", shape=circle, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n";
      else
	output<<vi<<"[label=\"\", width="<<width<<", shape=square, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n";
     


    }
  
  if(directed)
    {
      for(tie(eit,eitend)=edges(G);eit!=eitend;++eit)
	{
	  Edge e = *eit;
	  Vert u,v;
	  u = source(e,G);
	  v = target(e,G);

	  v_size_t ui = index[u];
	  v_size_t vi = index[v];

	  output<<ui<<" -- "<<vi<<";\n";
	}
    }
  else
    {
      cout<<"Graph viz undirected\n";
      UGraph UG((v_Usize_t) n );

      for(tie(eit,eitend)=edges(G);eit!=eitend;++eit)
	{
	  Edge e = *eit;
	  Vert s = source(e,G);
	  Vert t = target(e,G);

	  //	  cout<<"s "<<s<<" t "<<t<<"\n";

	  long ui = index[s];
	  long vi = index[t];

	  //cout<<"ui "<<ui<<" vi "<<vi<<"\n";

	  UVert u = vertex(ui,UG);
	  UVert v = vertex(vi,UG);

	  //cout<<"u "<<u<<" v "<<v<<"\n";

	  UEdge exist;
	  bool yes1,yes2;

	  tie(exist,yes1) = edge(u,v,UG);
	  tie(exist,yes2) = edge(v,u,UG);
	  if(!yes1 && !yes2)
	    add_edge(u,v,UG);
	}

      graph_traits<UGraph>::edge_iterator uit, uitend;
      property_map<UGraph, vertex_index_t>::type u_index = get(vertex_index,UG);

      for(tie(uit,uitend)=edges(UG);uit!=uitend;++uit)
	{
	  UEdge e = *uit;
	  UVert u,v;
	  u = source(e,UG);
	  v = target(e,UG);

	  long ui = u_index[u];
	  long vi = u_index[v];

	  long max_size = ui;
	  if (sizes[vi] > max_size)
	    max_size = vi;

	  output<<ui<<" -- "<<vi<<" [weight="<<node_weight[max_size]<<"];\n";
	}
    }

  output<<"}";
  output.close();
}
 int main () {
 int i , choice;
 int value;
 tree* newNode;
 printf(" \nEnter your choice :\n");
 printf("1. Create AVL tree.\n");
 printf("2. Inserting a node in AVL tree.\n");
 printf("3. Delete a node from the tree.\n");
 printf("4. Perform binary search.\n");
 printf("5. Find predecessor and successor of a node.\n");
 printf("6. Print AVL Tree\n");
 printf("\n   Press any other key to Exit.\n");
 scanf("%d" , &choice);
 
 
 while (1) {
 switch( choice ) {
 int n ,i , key;
 case 1 : //creation
 printf("How many nodes you want to insert\n");
 scanf("%d",&n);
 for ( i = 0 ; i < n ; i++) {
 printf("Enter the value\n");
 scanf("%d" ,&value);
 newNode = create (value);
 if (root == NULL)  //tree is empty.
 root = newNode;
 else
 root = insert( root , newNode);
 }
 break;
 
 case 2 : //inserte a node.
 printf("Enter the value\n");
 scanf("%d" ,&value);
 newNode = create (value);
 if (root == NULL) { //tree is empty.
 root = newNode;
 return;
 }
 root = insert ( root , newNode );
 //inorder(root);
 break;
 
 case 3 : //delete a node
 if(root == NULL) {
    printf("Tree is empty.\n");
    break;
 }
 printf("Enter the key which you want to delete :\n");
 scanf ("%d" ,&key);
 root = deletion (root , key);  
 //inorder(root);
 break;
 case 4 :
 if(root == NULL) {
    printf("Tree is empty.\n");
    break;
 }
 printf("Enter the key which you want to search :\n");
 scanf ("%d" ,&key);
 tree* loc;
 loc = (tree*)binarySearch ( root , key);
 if (loc==NULL)
   printf("The key %d is not present in AVL tree.\n",key);
 else
   printf("The key %d is present in AVL tree and its occurrence is =%d\n",key,loc->count);
 break;
 case 5 :
 printf("Enter the key for which you want to find predecessor and successor :\n");
 scanf ("%d" ,&key);
 findPredAndSucc ( root , key);
 break;
 
 case 6 :
      printf("\n\n");
      printTree ( root , 0); //printing tree in vertical fashion.
 break;
   
 default :
  exit(0);
 }
 printf(" \nEnter your choice :\n");
 printf("1. Create AVL tree.\n");
 printf("2. Inserting a node in AVL tree.\n");
 printf("3. Delete a node from the tree.\n");
 printf("4. Perform binary search.\n");
 printf("5. Find predecessor and successor of a node.\n");
 printf("6. Print AVL Tree\n");
 printf("\n   Press any other key to Exit.\n");
 scanf("%d" , &choice);
 
 }
 getch();
 return 0;
 }
Beispiel #7
0
int main(int argc, char *argv[])
{
    /*List *list = List_create();
    push(list, 5);
    push(list, 1);
    push(list, 1);
    push(list, 2);
    push(list, 0);

    bubble_sort(list);*/

    /*List *list = List_create();
    push(list, 2);
    push(list, 1);
    push(list, 5);
    push(list, 0);
    push(list, 1);
    push(list, 99);
    push(list, -7);
    printf("Unsorted list\n");
    List_print(list);

    printf("Sorted list\n");
    List *sorted = quick_sort(list);
    List_print(sorted);

    quick_sort(list);*/
    List *list = List_create();
    push(list, 5);
    push(list, 7);
    push(list, 9);
    push(list, 15);
    push(list, 20);

    int num;
    num = 20;
    int i = binarySearch(list, num);
    if(i==1)
    {
        printf("%d found in list.\n", num);
    }
    else
    {
        printf("%d not found in list.\n", num);
    }

    num = 5;
    i = binarySearch(list, num);
    if(i==1)
    {
        printf("%d found in list.\n", num);
    }
    else
    {
        printf("%d not found in list.\n", num);
    }

    num = 6;
    i = binarySearch(list, num);
    if(i==1)
    {
        printf("%d found in list.\n", num);
    }
    else
    {
        printf("%d not found in list.\n", num);
    }
    return 0;
}
Beispiel #8
0
    bool searchSubMatrixRecursive(
        vector<vector<int>>& matrix,
        int startRowIndex,     // index of start row of the search submatrix
        int startColumnIndex,  // index of start column of the search submatrix
        int cntRows,           // count of rows of the search submatrix
        int cntColumns,        // count of columns of the search submatrix
        int target)
    {
        // firstLarger is the one-dimensional index of the first element which is  
        // larger than target during the binary search.
        int firstLarger = -1;

        if (cntRows == 1)
        {
            // The submatrix has only one row, so just do the binary search 
            // for target in that row.
            return binarySearch(
                matrix,
                startRowIndex,
                startColumnIndex,
                1,
                cntColumns,
                target,
                0,
                cntColumns - 1,
                0,
                SearchDirection::RowFixed,
                firstLarger);
        }

        if (cntColumns == 1)
        {
            // The submatrix has only one column, so just do the binary search 
            // for target in that column.
            return binarySearch(
                matrix,
                startRowIndex,
                startColumnIndex,
                cntRows,
                1,
                target,
                0,
                cntRows - 1,
                0,
                SearchDirection::ColumnFixed,
                lowestLarger);
        }

        // Do the binary search along the diagonal. 
        if (binarySearch(
            matrix,
            startRowIndex,
            startColumnIndex,
            cntRows,
            cntColumns,
            target,
            0,
            max(cntRows, cntColumns) - 1,
            -1,
            SearchDirection::Diagonal,
            firstLarger))
        {
            return true;
        }

        if (firstLarger == -1)
        {
            // Since we can't find "firstLarger", target must not exist in matrix.
            return false;
        }

        // Convert the one-dimensional index "firstLarger" into the two-dimensional 
        // matrix index.
        pair<int, int> firstLargerIndexes = FromOneDimensionalIndexToTwoDimensionalIndexes(
            startRowIndex,
            startColumnIndex,
            cntRows,
            cntColumns,
            firstLarger,
            -1,
            SearchDirection::Diagonal);

        // If the "firstLarger" element is on the diagonal or the last column, 
        // target may be in the bottom left submatrix.
        if (firstLargerIndexes.first - startRowIndex >=
            firstLargerIndexes.second - startColumnIndex)
        {
            if (searchSubMatrixRecursive(
                matrix,
                firstLargerIndexes.first,
                startColumnIndex,
                cntRows - (firstLargerIndexes.first - startRowIndex),
                firstLargerIndexes.second - startColumnIndex,
                target))
            {
                return true;
            }
        }

        // If the "firstLarger" element is on the diagonal or the last row,
        // target may be in the top right submatrix.
        if (firstLargerIndexes.first - startRowIndex <=
            firstLargerIndexes.second - startColumnIndex)
        {
            if (searchSubMatrixRecursive(
                matrix,
                startRowIndex,
                firstLargerIndexes.second,
                firstLargerIndexes.first - startRowIndex,
                cntColumns - (firstLargerIndexes.second - startColumnIndex),
                target))
            {
                return true;
            }
        }

        return false;
    }
Beispiel #9
0
double ArizonaTest::getScale2Surface(double *dis)
{
	if (coords.empty() || indices.empty()) {
		DBGA("Unable to compute minimum force; hull not set");
		return 0;
	}
	if(mIsFlipped){
		dis[0] = - dis[0];
		dis[1] = - dis[1];
		dis[2] = - dis[2];
	}

	// compute the necessary force
	PQP_REAL v1[3],v2[3],v3[3];
	PQP_Model volume = PQP_Model();

	//model for the volumn
	volume.BeginModel();
	int triInd = 0;
	int numIndices = indices.size();
	for (int k = 0; k < numIndices - 3; k++) {
		if(indices[k+3] == -1) //  dealing with meaningful vertices.
		{
			v1[0]=coords[indices[k]].x();
			v1[1]=coords[indices[k]].y();
			v1[2]=coords[indices[k]].z();

			v2[0]=coords[indices[k+1]].x();
			v2[1]=coords[indices[k+1]].y();
			v2[2]=coords[indices[k+1]].z();

			v3[0]=coords[indices[k+2]].x();
			v3[1]=coords[indices[k+2]].y();
			v3[2]=coords[indices[k+2]].z();

			volume.AddTri(v1,v2,v3,triInd++);
		}
	}
	volume.EndModel();

	PQP_REAL pt[3];
	pt[0] = (double)(dis[0]*mGrasp->getMaxRadius());
	pt[1] = (double)(dis[1]*mGrasp->getMaxRadius());
	pt[2] = (double)(dis[2]*mGrasp->getMaxRadius());

	vec3 disturbance(pt[0], pt[1], pt[2]);
	double originalLength = disturbance.len();
	double startValue = 0, endValue = originalLength;

	int loops = 0;
	while (!isOutside(&volume, pt) ) {
		pt[0] *= 2; pt[1] *= 2; pt[2] *= 2;
		startValue = endValue;
		endValue *= 2;
		loops ++;
		if (loops > 20) {
			DBGA("Failed to find point outside of volume!!!!!");
			break;
		}
	}

	disturbance = normalise(disturbance);
	double length = binarySearch(disturbance, volume, startValue, endValue);

	return originalLength / length;
}
int main(){
    vector<int> array = {1, 2, 3, 3, 4, 5, 10};
    cout<<binarySearch(array, 3)<<endl;
    return 0;
}
Beispiel #11
0
// vrati index cisla x vo vzostupne usporiadanej postupnosti cisel. Vrati -1 ak sa x v postupnosti nenachadza.
int search(int cisla[], int n, int x)
{
  return binarySearch(cisla,n,0,n-1,x);
}
Beispiel #12
0
/* Negation across a range of the container.
 * Compute the  negation of src  and write the result
 * to *dst. Returns true if the result is a bitset container
 * and false for an array container.  *dst is not preallocated.
 */
bool array_container_negation_range(const array_container_t *src,
                                    const int range_start, const int range_end,
                                    void **dst) {
    /* close port of the Java implementation */
    if (range_start >= range_end) {
        *dst = array_container_clone(src);
        return false;
    }

    int32_t start_index =
        binarySearch(src->array, src->cardinality, (uint16_t)range_start);
    if (start_index < 0) start_index = -start_index - 1;

    int32_t last_index =
        binarySearch(src->array, src->cardinality, (uint16_t)(range_end - 1));
    if (last_index < 0) last_index = -last_index - 2;

    const int32_t current_values_in_range = last_index - start_index + 1;
    const int32_t span_to_be_flipped = range_end - range_start;
    const int32_t new_values_in_range =
        span_to_be_flipped - current_values_in_range;
    const int32_t cardinality_change =
        new_values_in_range - current_values_in_range;
    const int32_t new_cardinality = src->cardinality + cardinality_change;

    if (new_cardinality > DEFAULT_MAX_SIZE) {
        bitset_container_t *temp = bitset_container_from_array(src);
        bitset_flip_range(temp->array, (uint32_t)range_start,
                          (uint32_t)range_end);
        temp->cardinality = new_cardinality;
        *dst = temp;
        return true;
    }

    array_container_t *arr =
        array_container_create_given_capacity(new_cardinality);
    *dst = (void *)arr;
    if(new_cardinality == 0) {
      arr->cardinality = new_cardinality;
      return false; // we are done.
    }
    // copy stuff before the active area
    memcpy(arr->array, src->array, start_index * sizeof(uint16_t));

    // work on the range
    int32_t out_pos = start_index, in_pos = start_index;
    int32_t val_in_range = range_start;
    for (; val_in_range < range_end && in_pos <= last_index; ++val_in_range) {
        if ((uint16_t)val_in_range != src->array[in_pos]) {
            arr->array[out_pos++] = (uint16_t)val_in_range;
        } else {
            ++in_pos;
        }
    }
    for (; val_in_range < range_end; ++val_in_range)
        arr->array[out_pos++] = (uint16_t)val_in_range;

    // content after the active range
    memcpy(arr->array + out_pos, src->array + (last_index + 1),
           (src->cardinality - (last_index + 1)) * sizeof(uint16_t));
    arr->cardinality = new_cardinality;
    return false;
}
Beispiel #13
0
void test_to_search_element_from_the_list_of_integers_which_is_not_available() {
    int elements[5] = {4,6,7,8,2};
    int key = 9;
    int* result = binarySearch(elements,&key, 5, sizeof(int), compareInt);
    ASSERT((int*)result == NULL);
};
Beispiel #14
0
void test_to_search_element_from_the_list_of_characters_whichis_not_available() {
    char elements[3] = {'m','a','n'};
    char key = 'k';
    char* result = binarySearch(elements,&key, 3, sizeof(char), compareChar);
    ASSERT(NULL == (char*)result);
};
int  assignBWA_WSSD_ReadDepthFrom(FILE *fp7, FILE *fp8)
{
	int SVIdArray[500000];
	char SVNameTemp[100];
	int counSVNameList=0;
	char fileName[1000];
	char sample[100];
	int sampleId;
	FILE *fp9;
	int pos1, pos2;
	char chroName[10];
	float tempF, cnvCount;

	// Building list of SV names
	while(fscanf(fp8, "%s\n", SVNameTemp)!=EOF)
	{
		SVIdArray[counSVNameList]=binarySearch(0, countSV, SVNameTemp);
		counSVNameList++;
	}


int countLoci2=0;
	// Reading sample:file map file
	while(fscanf(fp7,"%s\t%s\n", fileName, sample)!=EOF)
	{
countLoci2=0;
		for (int count=0; count<totalNumSamples; count++)
		{
			if (strcmp(sample, samplesName[count])==0)
				sampleId=count;
		}

		fp9=fopen(fileName, "r");
		
		//chr10	74306	74825	CNV:1.938747	0.410072	0.018000	
		// Read depth file for each sample
		for (int count=0; count<counSVNameList; count++)
		{
			fscanf(fp9,"%s\t%i\t%i\tCNV:%f\t%f\t%f\n", chroName, &pos1, &pos2, &(listSV[SVIdArray[count]].wssdCNV_BWA[sampleId]), &tempF, &tempF);
		}
		

//		for (int count=0; count<countSV; count++)
//		{
		/*while(fscanf(fp9,"%s\t%i\t%i\tCNV:%f\t%f\t%f\n", chroName, &pos1, &pos2, &cnvCount, &tempF, &tempF)!=EOF)
		{
		countLoci2++;
		printf("%i %i\n", pos1, countLoci2);
			for (int count2=0; count2<countSV; count2++)
			{
				if (strcmp(chroName, listSV[count2].chroName)==0 && pos1==listSV[count2].posInnerLeft && listSV[count2].posInnerRight==pos2)
				{
					listSV[count2].wssdCNV_BWA[sampleId]=cnvCount;
					continue;
				}
			}


		}

		
		fclose(fp9);
	*/
	}
	

}
 vector<int> searchRange(vector<int>& nums, int target) {
     int start = binarySearch(nums,target,1);
     if(start>=nums.size() || nums[start]>target) return {-1,-1};
     int end = binarySearch(nums,target,0);
     return {start,end-1};
 }
int main(int argv, char *argc[])
{


	FILE *fp1=fopen(argc[1],"r");// Samples Name
	FILE *fp2=fopen(argc[2],"r");// the SV paired-end info 
//	FILE *fp3=fopen(argc[3],"r");// the number of windows
//	FILE *fp4=fopen(argc[4],"r");// wssd CNV (mrsFast/Peter version)	
	FILE *fp5=fopen(argc[3],"r");// Known ALu, L1 calls
	FILE *fp6=fopen(argc[4],"r");// probands name

	FILE *fp7=fopen(argc[5],"r");// read-depth BAM file using BWA mapping
	FILE *fp8=fopen(argc[6],"r");// the name of the SVs in the BWA readdepth7
	char tempStr[100];

	// Count sample names
	while(fscanf(fp1,"%s\n", samplesName[totalNumSamples])!=EOF)
	{
		totalNumSamples++;
	}

/*	for (int count=0; count<160; count++)
	{
	//	fscanf(fp1,"%s\t%s\t%s\t%s\n", samplesName[count], samplesOtherName[count], tempStr, tempStr);
		fscanf(fp1,"%s\n", samplesName[count]);
	}
*/


    //Read SV paired end info
	while(fscanf(fp2,"%s\t%i\t%i\t%s\t%i\t%f", listSV[countSV].chroName, &listSV[countSV].posInnerLeft, &listSV[countSV].posInnerRight, listSV[countSV].SVName, &listSV[countSV].totalSup, &listSV[countSV].averageEditDist)!=EOF)
	{
		for (int count=0; count<totalNumSamples; count++)
		{
			fscanf(fp2, "\t%i\t%f", &listSV[countSV].sampleSup[count], &listSV[countSV].sampleEditDist[count]);
			if (listSV[countSV].sampleSup[count]>0)
				listSV[countSV].genotypeArray[count]=1;
		}
		fscanf(fp2,"\n");
		countSV++;
	}

	printf("L253\n");
	
	qsort(listSV, countSV, sizeof(SV), compare);
	
	printf("L257\n");

//chr10   74306   74825   chr10_5 0

	char chroName[10];
	int pos1, pos2, winCount;
	char SVName[20];
	char tempSampleName[100];

	while(fscanf(fp6,"%s\n", tempSampleName)!=EOF)
	{
		for (int count=0; count<totalNumSamples; count++)
		{
			if (strcmp(tempSampleName,samplesName[count])==0)
			{
				isProbandOrSibling[count]=1;
			}
		} 
	}

//contig  start   end     name    SSC05075        SSC06572        SSC06563        SSC07807        SSC07806        SSC05066        SSC07802        SSC05070        SSC09060     SSC10379        SSC09067        SSC07131        SSC04980        SSC07130        SSC04987        SSC04986        SSC08188        SSC08185        SSC09514    SSC08187 SSC08518


	int SVIdFound=0;
	/*
	while(fscanf(fp3,"%s\t%i\t%i\t%s\t%i\n", chroName, &pos1, &pos2, SVName, &winCount)!=EOF)
	{
		SVIdFound=binarySearch(0, countSV-1, SVName);
		//if (strcmp(SVName, listSV[count].SVName)==0)
		listSV[SVIdFound].windowsCovered=winCount;
	}*/

	//printf("L115\n");

/*
	fscanf(fp5,"%s\t%i\t%i\n", chroName, pos1, pos2)
	{
		for (int count=0; count<countSV; count++)
		{
			if ((listSV[countSV].posInnerRight-listSV[countSV].posInnerLeft>300 && listSV[countSV].posInnerRight-listSV[countSV].posInnerLeft<500)||(listSV[countSV].posInnerRight-listSV[countSV].posInnerLeft>5000 && listSV[countSV].posInnerRight-listSV[countSV].posInnerLeft<7000))
			{
				if (strcmp(chroName, listSV[countSV].chroName)==0)
				{
					if (listSV[countSV].posInnerRight>pos1 && listSV[countSV].posInnerLeft<pos1 && listSV[countSV].posInnerRight-100<pos1 && listSV[countSV].posInnerLeft+100>pos1)
					{
						listSV[SVIdFound].MEIgoodCall=true;						
					}
				}
			}
		}	
	}

*/

/*	fscanf(fp4,"contig\tstart\tend");
	for (int count=0; count<160; count++)
	{
		fscanf(fp4,"\t%s", wssdSamplesName[count]);
		for (int count2=0; count2<160; count2++)
		{
			if (strcmp(wssdSamplesName[count], samplesName[count2])==0)
				convertWSSDSampleNameToSV[count]=count2;
		}
	}    
	fscanf(fp4,"\n");
*/

	//printf("L131\n");	

/*	for (int count=0; count<countSV; count++)
	{
		fscanf(fp4,"%s\t%i\t%i\t%s", chroName, &pos1, &pos2, SVName);
	//	if (strcmp(SVName, listSV[count].SVName)!=0)
	//		printf("EROROROROR\n");
		SVIdFound=binarySearch(0, countSV-1, SVName);
		//printf("%i\t%s\t%s\n", SVIdFound, listSV[SVIdFound].SVName, SVName); 
		for (int count2=0; count2<160; count2++)
		{
			fscanf(fp4, "\t%f", &listSV[SVIdFound].wssdCNV[convertWSSDSampleNameToSV[count2]]);
		}	
		fscanf(fp4,"\n");
	

	
	}
*/

	while(fscanf(fp5, "%s\n", SVName)!=EOF)
	{
		SVIdFound=binarySearch(0, countSV-1, SVName);
	
		listSV[SVIdFound].MEIgoodCall=true;
		listSV[SVIdFound].goodCall=true;
	}

	printf("L150\n");

	assignBWA_WSSD_ReadDepthFrom(fp7,fp8);

	printf("L232\n");	
	int countTemp=0;
	//float sumCNV1=0;
	float sumCNV1_BWA=0;
	
	//float sumCNV2=0;
	float sumCNV2_BWA=0;
	
	int maxSup;

	for (int count=0; count<countSV; count++)
	{
	countTemp=0;
	//sumCNV1=0;
	sumCNV1_BWA=0;
	//sumCNV2=0;
	sumCNV2_BWA=0;
	maxSup=0;
		//if (listSV[count].windowsCovered>0)
		{
			for (int count2=0; count2<totalNumSamples; count2++)
			{
				if (listSV[count].sampleSup[count2]>0)
				{
					countTemp++;
					//sumCNV1=sumCNV1+listSV[count].wssdCNV[count2];
					sumCNV1_BWA=sumCNV1_BWA+listSV[count].wssdCNV_BWA[count2];
					if (listSV[count].sampleSup[count2]>maxSup)
						maxSup=listSV[count].sampleSup[count2];
				}
				else{
					//sumCNV2=sumCNV2+listSV[count].wssdCNV[count2];
					sumCNV2_BWA=sumCNV2_BWA+listSV[count].wssdCNV_BWA[count2];
				}
			}
			listSV[count].maxSup=maxSup;
		//printf("%s\t%i\t%i\t%i\t%f\t%f\t%i\t%i\t%s\n", listSV[count].chroName, listSV[count].posInnerLeft, listSV[count].posInnerRight, listSV[count].windowsCovered, (float)sumCNV1/(float)countTemp, (float)sumCNV2/(float)(160-countTemp), listSV[count].totalSup, maxSup, listSV[count].SVName);
		/*	if (listSV[count].windowsCovered>0 && (float)sumCNV1/(float)countTemp<1.4 && (float)sumCNV2/(float)(160-countTemp) - (float)sumCNV1/(float)countTemp > 0.6)
			{
				listSV[count].goodCall=true;
				listSV[count].mrsFastReadDepthGoodCall=true;
				for (int count2=0; count2<maxNumSamples; count2++)
				{
					if (listSV[count].wssdCNV[count2]<1.4 && listSV[count].sampleSup[count2]==0)
					{
						listSV[count].genotypeArray[count2]=1;
					}
					if (listSV[count].wssdCNV[count2]>1.6 && listSV[count].sampleSup[count2]>0)
					{
						listSV[count].genotypeArray[count2]=0;
					}
				}
				listSV[count].CNV1_mrsFast=(float)sumCNV1/(float)countTemp;
				listSV[count].CNV2_mrsFast=(float)sumCNV2/(float)(160-countTemp);
				listSV[count].CNV1_BWA=(float)sumCNV1_BWA/(float)countTemp;
				listSV[count].CNV2_BWA=(float)sumCNV2_BWA/(float)(160-countTemp);
				
			}else //if (listSV[count].windowsCovered==0 && (float)sumCNV1_BWA/(float)countTemp<1.4 && (float)sumCNV2_BWA/(float)(160-countTemp) - (float)sumCNV1_BWA/(float)countTemp > 0.6)
		*/	
		if ((float)sumCNV1_BWA/(float)countTemp<1.4 && (float)sumCNV2_BWA/(float)(totalNumSamples-countTemp) - (float)sumCNV1_BWA/(float)countTemp > 0.6)
			{
				
				listSV[count].bwaReadDepthGoodCall=true;
				listSV[count].goodCall=true;
				//listSV[count].realGoodCall=true;
				for (int count2=0; count2<maxNumSamples; count2++)
				{
					if (listSV[count].wssdCNV_BWA[count2]<1.4 && listSV[count].sampleSup[count2]==0)
					{
						listSV[count].genotypeArray[count2]=1;
					}
					if (listSV[count].wssdCNV_BWA[count2]>1.6 && listSV[count].sampleSup[count2]>0)
					{
						listSV[count].genotypeArray[count2]=0;
					}
				}
				listSV[count].CNV1_BWA=(float)sumCNV1_BWA/(float)countTemp;
				listSV[count].CNV2_BWA=(float)sumCNV2_BWA/(float)(totalNumSamples-countTemp);
			} /*else if ((float)sumCNV1_BWA/(float)countTemp<1)
			{
				listSV[count].bwaReadDepthGoodCall=true;
				listSV[count].goodCall=true;
			}*/
		}
	}



	for (int count=0; count<countSV; count++)
	{
		if (listSV[count].posInnerRight-listSV[count].posInnerLeft>750 && listSV[count].maxSup>5 && listSV[count].totalSup>10 && listSV[count].goodCall==false)
		//if (listSV[count].posInnerRight-listSV[count].posInnerLeft>750 && listSV[count].maxSup>5 && listSV[count].totalSup>10 && listSV[count].goodCall==false)
		{
		countTemp=0;
		sumCNV1_BWA=0;
		sumCNV2_BWA=0;
			listSV[count].goodCall=true;
			
			for (int count2=0; count2<totalNumSamples; count2++)
			{
				if (listSV[count].sampleSup[count2]>0)
				{
					countTemp++;
					//sumCNV1=sumCNV1+listSV[count].wssdCNV[count2];
					sumCNV1_BWA=sumCNV1_BWA+listSV[count].wssdCNV_BWA[count2];
					//if (listSV[count].sampleSup[count2]>maxSup)
					//	maxSup=listSV[count].sampleSup[count2];
				}
				else{
					//sumCNV2=sumCNV2+listSV[count].wssdCNV[count2];
					sumCNV2_BWA=sumCNV2_BWA+listSV[count].wssdCNV_BWA[count2];
				}
			}
		
			listSV[count].CNV1_BWA=(float)sumCNV1_BWA/(float)countTemp;
			listSV[count].CNV2_BWA=(float)sumCNV2_BWA/(float)(totalNumSamples-countTemp);

		}
			
	}


	int genotypeCount=0;
	int numProbandSib=0;
	int denovoSampleId=0;

	printf("Chro\tPos1\tPos2\tSVName\tTotalSup\tMaxSup");
	for (int count=0; count<totalNumSamples;count++)
	{
		printf("\t%s", samplesName[count]);		
	}
	printf("\n");
		

	for (int count=0; count<countSV; count++)
	{
	genotypeCount=0;
	numProbandSib=0;
	denovoSampleId=0;
		if (listSV[count].goodCall==true)
		{

			for (int count2=0; count2<totalNumSamples; count2++)
			{
				if (listSV[count].genotypeArray[count2]==1)
				{
					genotypeCount++;
				}
				if (listSV[count].genotypeArray[count2]==1 &&  isProbandOrSibling[count2]==1)
				{
					numProbandSib++;
					denovoSampleId=count2;
				}
			}
			for (int count2=0; count2<totalNumSamples; count2++)
			{
			//chr10	131095256	131096444	1	SSC10104	chr10_100117	
				if (listSV[count].genotypeArray[count2]==1)
				{
					if (!(listSV[count].bwaReadDepthGoodCall==false && listSV[count].MEIgoodCall==false && genotypeCount>totalNumSamples*0.9))
					{
						printf("%s\t%i\t%i\t1\t%s\t%s", listSV[count].chroName, listSV[count].posInnerLeft, listSV[count].posInnerRight, samplesName[count2], listSV[count].SVName);
						if (listSV[count].MEIgoodCall==true)
							printf("\tMEI");
						else if (listSV[count].bwaReadDepthGoodCall==true)
							printf("\tReadDepth");
						if (numProbandSib==1 && genotypeCount==1)
							printf("\tDeNovo\n");
						else printf("\n");
					}
				}
			}
		}
	}
	


}
int main() {
    int i, option;
    Tree* BinarySearchTree = createEmptyTree();
    TreeAVL* AVLTree = createEmptyAVLTree();
    printf("Count and plot data\nBinary Search Tree vs. AVL Tree\n\n");
    printf("To continue, type 1\nTo exit, type ant other key\n\n");
    printf("Your option: ");
    scanf("%d", &option);

    if(option == 1) {
        for(i = 0; i < 10000; i++) {
            BinarySearchTree = insertNode(BinarySearchTree, i);
            AVLTree = insertNodeAVL(AVLTree, i);
        }

        printf("\nNumber of comparisons to find %d in the AVL Tree: %d\n", i - 1, binarySearchAVL(AVLTree, i - 1, 0));
        printf("Number of comparisons to find %d in the Binary Search Tree: %d\n", i - 1, binarySearch(BinarySearchTree, i - 1, 0));
    }

    return 0;
}
Beispiel #19
0
 int kthSmallest(TreeNode* root, int k) {
     vector<int> nums;
     Inorder(root, nums);
     int ans = binarySearch(nums,k-1);
     return ans;
 }
Beispiel #20
0
void addName2Set(Set set, char *str) {
	int searchresult = binarySearch(names, str, 0, 320);
	add2Set(set, searchresult);
}
 bool searchMatrix(vector<vector<int>>& matrix, int target) {
     return binarySearch(matrix,0, matrix.size()*matrix[0].size()-1,target);
     
 }
Beispiel #22
0
void deleteNameFromSet(Set set, char *str) {
	int searchresult = binarySearch(names, str, 0, 320);
	deleteFromSet(set, searchresult);
}
/*
  This function produces a graphviz file of the graph passed to it,
  but it colors the nodes based on the colors provided in color.  All
  nodes are same size, though the nodes in the vector square_nodes are
  doubled in size and square as a way of highlighting important nodes.
 */
void write_graphviz(Graph & G, string output_file, vector<double> color, vector<int> square_nodes, bool directed)
{
  ofstream output;
  output.open(output_file.c_str());

  double min = color[0];
  double max = color[0];

  v_size_t n = num_vertices(G);

  for(size_t i = 0; i < color.size(); ++i)
    {
      if(color[i]>max)
	max = color[i];

      if(color[i]<min)
	min = color[i];
    }


  output<<"Graph color {\n";
  output<<"splines=false;\n";

  graph_traits<Graph>::edge_iterator eit, eitend;
  graph_traits<Graph>::vertex_iterator vit, vitend;

  property_map<Graph, vertex_index_t>::type index = get(vertex_index,G);

  for (tie(vit,vitend) = vertices(G); vit != vitend; ++vit)
    {

      Vert      v = *vit;
      v_size_t vi = index[v];
      char rgb[8];
      double width=0.2;      
      double val;
      
      if (color.size() != n && G[v].prevIndices.size() != 0)
	val = ((double) color[G[v].prevIndices[0]] - min) / (double) (max - min);
      else
	val = ((double) color[vi] - min) / (double) (max - min);

      get_rgb_value(rgb,val);

      int found = binarySearch(square_nodes,vi);
      
      if(found==-1)
	output<<vi<<"[label=\"\", width="<<width<<", shape=circle, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n";
      else
	output<<vi<<"[label=\"\", width="<<2.0*width<<", shape=square, style=\"filled\", fillcolor=\""<<rgb<<"\"];\n";

    }
  
  if(directed)
    {
      for(tie(eit,eitend)=edges(G);eit!=eitend;++eit)
	{
	  Edge e = *eit;
	  Vert u,v;
	  u = source(e,G);
	  v = target(e,G);

	  v_size_t ui = index[u];
	  v_size_t vi = index[v];

	  output<<ui<<" -- "<<vi<<";\n";
	}
    }
  else
    {
      cout<<"Graph viz undirected\n";
      UGraph UG((v_Usize_t) n );

      for(tie(eit,eitend)=edges(G);eit!=eitend;++eit)
	{
	  Edge e = *eit;
	  Vert s = source(e,G);
	  Vert t = target(e,G);

	  //	  cout<<"s "<<s<<" t "<<t<<"\n";

	  long ui = index[s];
	  long vi = index[t];

	  //cout<<"ui "<<ui<<" vi "<<vi<<"\n";

	  UVert u = vertex(ui,UG);
	  UVert v = vertex(vi,UG);

	  //cout<<"u "<<u<<" v "<<v<<"\n";

	  UEdge exist;
	  bool yes1,yes2;

	  tie(exist,yes1) = edge(u,v,UG);
	  tie(exist,yes2) = edge(v,u,UG);
	  if(!yes1 && !yes2)
	    add_edge(u,v,UG);
	}

      graph_traits<UGraph>::edge_iterator uit, uitend;
      property_map<UGraph, vertex_index_t>::type u_index = get(vertex_index,UG);

      for(tie(uit,uitend)=edges(UG);uit!=uitend;++uit)
	{
	  UEdge e = *uit;
	  UVert u,v;
	  u = source(e,UG);
	  v = target(e,UG);

	  long ui = u_index[u];
	  long vi = u_index[v];

	  output<<ui<<" -- "<<vi<<";\n";
	}
    }

  output<<"}";
  output.close();
}
Beispiel #24
0
 int mySqrt(int x) {
     return binarySearch(1, x, x);
 }
Beispiel #25
0
int main(int argc, char const *argv[])
{
	int a[] = {1,2,3,4,5,6,7,8};
	printf("%d\n", binarySearch(a,5,8));
	return 0;
}
Beispiel #26
0
void mexFunction( int nlhs, mxArray *plhs[],
                 int nrhs, const mxArray *prhs[] )  {
    
    // INPUT:
    double *pdData, *pdItems;
    double dirIfFound    = DIR_IF_FOUND_DEFAULT;     // default value
    double dirIfNotFound = DIR_IF_NOT_FOUND_DEFAULT; // default value
    
    // OUTPUT:
    double *pdPos;        
    
    // Local:    
    long i, N, nItems;
    int checkIfSorted;
    mwSize  nrows,ncols;
    const mxArray * pArg;
    char *pArgStr;

    const mwSize    *dims;    
    mwSize          numDims;        
    
    /* --------------- Check inputs ---------------------*/
    if (nrhs < 2)
        mexErrMsgTxt("at least 2 inputs required");
    if (nrhs > 5)  
        mexErrMsgTxt("maximum of 5 inputs");
    
    /// ------------------- data ----------
	pArg = prhs[0];
    nrows = mxGetM(pArg); ncols = mxGetN(pArg);
	if(!mxIsNumeric(pArg) || !mxIsDouble(pArg) || mxIsEmpty(pArg) || mxIsComplex(pArg) || ((nrows > 1) && (ncols >1)) ) { 
            mexErrMsgTxt("Input 1 (data) must be a noncomplex vector of doubles.");
    }
    pdData  = mxGetPr(prhs[0])-1; // subtract 1  for 1..N indexing
    N = nrows * ncols;
    
    /// ------------------- items ----------
    pArg = prhs[1];
    nrows = mxGetM(pArg); ncols = mxGetN(pArg);
	if(!mxIsNumeric(pArg) || !mxIsDouble(pArg) || mxIsEmpty(pArg) || mxIsComplex(pArg) ) { 
            mexErrMsgTxt("Input 2 (items) must be a noncomplex double matrix.");
    }
    pdItems = mxGetPr(prhs[1])-1;    
    nItems = nrows * ncols;

    /// ------------------- dirIfFound ----------
    if (nrhs >= 3) {
        
        pArg = prhs[2];
        if (mxIsEmpty(pArg)) {            
            dirIfFound = DIR_IF_FOUND_DEFAULT;  
        } else if (mxIsChar(pArg)) {
            pArgStr = mxArrayToString(pArg);
            if (strcmp(pArgStr, "first")==0) {
                dirIfFound = -1.0;       
            } else if (strcmp(pArgStr, "last")==0) {
                dirIfFound = 1.0;
            } else if (strcmp(pArgStr, "any")==0)
                dirIfFound = 0.0;
            else 
                mexErrMsgTxt("Input 3 (dirIfFound), if input as a string, must be either 'first', 'last', or 'any'");
        } else {
            if(!mxIsNumeric(pArg)  || mxIsComplex(pArg) || mxGetN(pArg)*mxGetM(pArg) != 1)
                mexErrMsgTxt("Input 3 (dirIfFound) must be a real scalar or a string");

            dirIfFound = mxGetScalar(prhs[2]);
        
            if (!( (dirIfFound == -1) || (dirIfFound == 0) || (dirIfFound == 1) )  )
                mexErrMsgTxt("Input 3 (dirIfFound) must be either -1, 0, or 1");
        }
    }
    
    /// ------------------- dirIfNotFound ----------
    if (nrhs >= 4) {
        pArg = prhs[3];
        if (mxIsEmpty(pArg)) {            
            dirIfNotFound == DIR_IF_NOT_FOUND_DEFAULT;  // default value
        } else if (mxIsChar(pArg)) {  
            pArgStr = mxArrayToString(pArg);
            if (strcmp(pArgStr, "exact")==0)
                dirIfNotFound = 0.0;
            else if (strcmp(pArgStr, "down")==0)
                dirIfNotFound = -1.0;
            else if (strcmp(pArgStr, "up")==0)
                dirIfNotFound = 1.0;
            else if (strcmp(pArgStr, "closest")==0)
                dirIfNotFound = 2.0;
            else if (strcmp(pArgStr, "frac")==0)
                dirIfNotFound = 0.5;
            else 
                mexErrMsgTxt("Input 4 (dirIfNotFound), if input as a string, must be either 'exact', 'down', 'up', 'closest', or 'frac'");
        } else {  
            if (!mxIsNumeric(pArg) || mxIsComplex(pArg) || mxGetN(pArg)*mxGetM(pArg) != 1) {
                mexErrMsgTxt("Input 4 (dirIfNotFound) must be a real scalar"); 
            } 
            dirIfNotFound = mxGetScalar(prhs[3]);

            if (!  ((dirIfNotFound == -1) || (dirIfNotFound == 0) || (dirIfNotFound == 0.5) || (dirIfNotFound == 1) || (dirIfNotFound == 2)) )
                mexErrMsgTxt("Input 4 (dirIfNotFound) must be either -1, 0, 1, 2, or 0.5");
        }
    }

    checkIfSorted = CHECK_IF_INPUT_SORTED_DEFAULT;
    if (nrhs == 5) {
        if (!mxIsEmpty(prhs[4]))
            checkIfSorted = 1;
    }

    if (checkIfSorted) {
        if (!issorted(pdData, N)) 
            mexErrMsgTxt("Input 1 (data) must be sorted.");
    }
   
    /// ------------------- pos (OUTPUT)----------    
    numDims = mxGetNumberOfDimensions(prhs[1]);  // this outputs with the same dimensions as the input
    dims = mxGetDimensions(prhs[1]);    
    plhs[0] = mxCreateNumericArray(numDims, dims, mxDOUBLE_CLASS, mxREAL);
        
    pdPos = mxGetPr(plhs[0])-1;

    // CALL BINARY SEARCH FUNCTION;
    for (i=1; i<=nItems; i++) {
        pdPos[i] = binarySearch(pdData, N, pdItems[i], dirIfFound, dirIfNotFound);
    }

}
 int searchInsert(vector<int>& nums, int target) {
     return binarySearch(0,nums.size()-1,target,nums);
 }
Beispiel #28
0
/**
 * Returns true if value is in array of n values, else false.
 */
bool search(int value, int values[], int n)
{
    return binarySearch(value, values, n);
}
Beispiel #29
0
void *ra_get_writable_container(roaring_array_t *ra, uint16_t x, uint8_t *typecode) {
    int i = binarySearch(ra->keys, (int32_t)ra->size, x);
    if (i < 0) return NULL;
    *typecode = ra->typecodes[i];
    return get_writable_copy_if_shared(ra->containers[i], typecode);
}
Beispiel #30
0
void test_search_element_from_the_list_of_floats_which_is_not_available() {
    float elements[5] = {4.7f,6.4f,7.3f,8.5f,2.2f};
    float key = 4.6f;
    float* result = binarySearch(elements,&key, 5, sizeof(float), compareInt);
    ASSERT(NULL == (float*)result);
};