Exemplo n.º 1
0
int main()
{
#if (Q == 1) || (Q == 2)
#  if Q == 1
  xx_trace_init("tp2q1");
  fprintf(xx_trace, "linear_search(..., 0, ..., ...) == %u\n",
	  linear_search(0, 0, 0, 0));
#  else
  xx_trace_init("tp2q2");
  fprintf(xx_trace, "binary_search(..., 0, ..., ...) == %u\n",
	  binary_search(0, 0, 0, 0));
#  endif
  const unsigned asize = (1U << 17) - 1;
  int a[asize];
  fprintf(xx_trace, "initializing a[%u] = { ... }\n", asize);
  for (unsigned i = 0; i < asize; ++i)
    a[i] = (int) xx_ranval();
  int b[13];
  int c[13];
  int d[13];
  memcpy(b, a, sizeof(b));
  b[10] = -2147483647 - 1;
  b[11] = 0;
  b[12] = 2147483647;
  fprintf(xx_trace, "set b[] of values to lookup\n");
  print_int_array(xx_trace, b, 13);
  qsort(a, asize, sizeof(*a), xx_cmpp);
  for (unsigned i = 0; i < 13; ++i)
    {
      xx_cmp_count = 0;
#  if Q == 1
      c[i] = linear_search(a, asize, b[i], xx_cmp);
#  else
      c[i] = binary_search(a, asize, b[i], xx_cmp);
#  endif
      d[i] = xx_cmp_count;
    }
  fprintf(xx_trace, "resulting indices in a[]\n");
  print_int_array(xx_trace, c, 13);
  fprintf(xx_trace, "number of comparisons in each case\n");
  print_int_array(xx_trace, d, 13);
  xx_trace_done();
#elif Q == 3
  xx_trace_init("tp2q3");
  const unsigned asize = 80 + (xx_ranval() % 32);
  int a[asize];
  fprintf(xx_trace, "initializing a[%u] = { ... }\n", asize);
  for (unsigned i = 0; i < asize; ++i)
    a[i] = (int) xx_ranval();
  xx_cmp_count = 0;
  bs_insert_sort_cmp(a, asize, xx_cmp);
  fprintf(xx_trace,
	  "bs_insert_sort_cmp(a,...) made %d comparisons\n",
	  xx_cmp_count);
  print_int_array(xx_trace, a, asize);
  xx_trace_done();
#elif Q == 4
  xx_trace_init("tp2q4");
  const unsigned asize = 100000;
  int a[asize];
  fprintf(xx_trace, "initializing a[%u] = { ... }\n", asize);
  int val = -1000000;
  for (unsigned i = 0; i < asize; ++i)
    a[i] = val += 1 + (xx_ranval() % 40);
  int a2[asize];
  memcpy(a2, a, sizeof(a));
  qsort(a2, asize, sizeof(*a), xx_gtp);
  int b[13];
  for (unsigned i = 0; i < 10; ++i)
    b[i] = (xx_ranval() % 2000000) - 1000000;
  b[10] = -2147483647 - 1;
  b[11] = 0;
  b[12] = 2147483647;
  fprintf(xx_trace, "set b[] of values to lookup\n");
  print_int_array(xx_trace, b, 13);
  int c[13];
  int c2[13];
  for (unsigned i = 0; i < 13; ++i)
    {
      c[i] = interpolate(a, 0, asize - 1, b[i], xx_lt);
      c2[i] = interpolate(a2, 0, asize - 1, b[i], xx_gt);
    }
  fprintf(xx_trace, "resulting indices in a[]\n");
  print_int_array(xx_trace, c, 13);
  fprintf(xx_trace, "resulting indices in a2[]\n");
  print_int_array(xx_trace, c2, 13);
  xx_trace_done();
#elif Q == 5
  xx_trace_init("tp2q5");
  fprintf(xx_trace, "interpolation_search(..., 0, ..., ...) == %u\n",
	  interpolation_search(0, 0, 0, 0));
  const unsigned asize = 100000;
  int a[asize];
  fprintf(xx_trace, "initializing a[%u] = { ... }\n", asize);
  int val = -1000000;
  for (unsigned i = 0; i < asize; ++i)
    a[i] = val += 1 + (xx_ranval() % 40);
  int a2[asize];
  memcpy(a2, a, sizeof(a));
  qsort(a2, asize, sizeof(*a), xx_gtp);
  int b[13];
  for (unsigned i = 0; i < 10; ++i)
    b[i] = (xx_ranval() % 2000000) - 1000000;
  b[10] = -2147483647 - 1;
  b[11] = 0;
  b[12] = 2147483647;
  fprintf(xx_trace, "set b[] of values to lookup\n");
  print_int_array(xx_trace, b, 13);
  int c[13];
  int c2[13];
  for (unsigned i = 0; i < 13; ++i)
    {
      c[i] = interpolation_search(a, asize, b[i], xx_lt);
      c2[i] = interpolation_search(a2, asize, b[i], xx_gt);
    }
  fprintf(xx_trace, "resulting indices in a[]\n");
  print_int_array(xx_trace, c, 13);
  fprintf(xx_trace, "resulting indices in a2[]\n");
  print_int_array(xx_trace, c2, 13);
  xx_trace_done();
#else
  puts("Compile with -DQ=n, where n is the question number.");
#endif
  return 0;
}
Exemplo n.º 2
0
void main(void)
{
	binary_search(8);
}
QgsFeatureId QgsTessellatedPolygonGeometry::triangleIndexToFeatureId( uint triangleIndex ) const
{
  int i = binary_search( triangleIndex, mTriangleIndexStartingIndices.constData(), mTriangleIndexStartingIndices.count() );
  Q_ASSERT( i != -1 );
  return mTriangleIndexFids[i];
}
Exemplo n.º 4
0
int 
main(int argc, char **argv)
{
	binary_search(8);
	return (0);
}
Exemplo n.º 5
0
/* This is the hottest code in Ag. 10-15% of all execution time is spent here */
static int path_ignore_search(const ignores *ig, const wchar_t *path, const wchar_t *filename) {
    wchar_t *temp;
    size_t i;
    int match_pos;

    match_pos = binary_search(filename, ig->names, 0, ig->names_len);
    if (match_pos >= 0) {
        log_debug(L"file %s ignored because name matches static pattern %s", filename, ig->names[match_pos]);
        return 1;
    }

    ag_asprintf(&temp, L"%s/%s", path[0] == '.' ? path + 1 : path, filename);

    if (wcsncmp(temp, ig->abs_path, ig->abs_path_len) == 0) {
		wchar_t *slash_filename = temp + ig->abs_path_len;
        if (slash_filename[0] == '/') {
            slash_filename++;
        }
        match_pos = binary_search(slash_filename, ig->names, 0, ig->names_len);
        if (match_pos >= 0) {
            log_debug(L"file %s ignored because name matches static pattern %s", temp, ig->names[match_pos]);
            free(temp);
            return 1;
        }

        match_pos = binary_search(slash_filename, ig->slash_names, 0, ig->slash_names_len);
        if (match_pos >= 0) {
            log_debug(L"file %s ignored because name matches slash static pattern %s", slash_filename, ig->slash_names[match_pos]);
            free(temp);
            return 1;
        }

        for (i = 0; i < ig->names_len; i++) {
			wchar_t *pos = wcsstr(slash_filename, ig->names[i]);
            if (pos == slash_filename || (pos && *(pos - 1) == '/')) {
                pos += wcslen(ig->names[i]);
                if (*pos == '\0' || *pos == '/') {
                    log_debug(L"file %s ignored because path somewhere matches name %s", slash_filename, ig->names[i]);
                    free(temp);
                    return 1;
                }
            }
            log_debug(L"pattern %s doesn't match path %s", ig->names[i], slash_filename);
        }

        for (i = 0; i < ig->slash_regexes_len; i++) {
            if (fnmatch(ig->slash_regexes[i], slash_filename, fnmatch_flags) == 0) {
                log_debug(L"file %s ignored because name matches slash regex pattern %s", slash_filename, ig->slash_regexes[i]);
                free(temp);
                return 1;
            }
            log_debug(L"pattern %s doesn't match slash file %s", ig->slash_regexes[i], slash_filename);
        }
    }

    for (i = 0; i < ig->regexes_len; i++) {
        if (fnmatch(ig->regexes[i], filename, fnmatch_flags) == 0) {
            log_debug(L"file %s ignored because name matches regex pattern %s", filename, ig->regexes[i]);
            free(temp);
            return 1;
        }
        log_debug(L"pattern %s doesn't match file %s", ig->regexes[i], filename);
    }

    int rv = ackmate_dir_match(temp);
    free(temp);
    return rv;
}
Exemplo n.º 6
0
 bool operator()(const typename boost::iterator_value<I>::type& x) const
 { return binary_search(first, last, x, compare) != last; }
Exemplo n.º 7
0
/**
   @brief Returns the next hashtable size.

   @param current The current size of the hash table.
   @returns The next size in the sequence for hash tables.
 */
int ht_next_size(int current)
{
  int curridx = binary_search(ht_primes, nelem(ht_primes), current);
  return ht_primes[curridx + 1];
}
Exemplo n.º 8
0
/*============================
	FIND INDEX
============================*/
int find_index_of_song_with_name(char* key) 
{
	return binary_search(key, 0, song_count-1);
}
Exemplo n.º 9
0
int build_subgraph(deque<set<int> > & E, const deque<int> & nodes, const deque<int> & degrees) {
	
	
	/*
	cout<<"nodes"<<endl;
	prints(nodes);
	
	cout<<"degrees"<<endl;
	prints(degrees);
	*/
	

	
	if(degrees.size()<3) {
		
		cerr<<"it seems that some communities should have only 2 nodes! This does not make much sense (in my opinion) Please change some parameters!"<<endl;
		return -1;
	
	}
	
	// this function is to build a network with the labels stored in nodes and the degree seq in degrees (correspondence is based on the vectorial index)
	// the only complication is that you don't want the nodes to have neighbors they already have
	
	
	
	// labels will be placed in the end
	deque<set<int> > en; // this is the E of the subgraph

	{
		set<int> first;
		for(int i=0; i<nodes.size(); i++) 
			en.push_back(first);
	}
	
	
	
	multimap <int, int> degree_node;
	
	for(int i=0; i<degrees.size(); i++)
		degree_node.insert(degree_node.end(), make_pair(degrees[i], i));
	
	int var=0;

	while (degree_node.size() > 0) {
		
		multimap<int, int>::iterator itlast= degree_node.end();
		itlast--;
		
		multimap <int, int>::iterator itit= itlast;
		deque <multimap<int, int>::iterator> erasenda;
		
		int inserted=0;
		
		for (int i=0; i<itlast->first; i++) {
			
			if(itit!=degree_node.begin()) {
			
				itit--;
				
				
				en[itlast->second].insert(itit->second);
				en[itit->second].insert(itlast->second);
				inserted++;
				
				erasenda.push_back(itit);				
				
			}
			
			else
				break;
		
		}
		
		
		for (int i=0; i<erasenda.size(); i++) {
			
			
			if(erasenda[i]->first>1)
				degree_node.insert(make_pair(erasenda[i]->first - 1, erasenda[i]->second));
	
			degree_node.erase(erasenda[i]);
		
		}

		
		var+= itlast->first - inserted;
		degree_node.erase(itlast);
		
	}

	
	
	// this is to randomize the subgraph -------------------------------------------------------------------
	
	for(int node_a=0; node_a<degrees.size(); node_a++) for(int krm=0; krm<en[node_a].size(); krm++) {
	
					
				
		int random_mate=irand(degrees.size()-1);
		while (random_mate==node_a)
			random_mate=irand(degrees.size()-1);
				
		
		if (en[node_a].insert(random_mate).second) {
			
			deque <int> out_nodes;
			for (set<int>::iterator it_est=en[node_a].begin(); it_est!=en[node_a].end(); it_est++) if ((*it_est)!=random_mate)
				out_nodes.push_back(*it_est);
						
										
					
			int old_node=out_nodes[irand(out_nodes.size()-1)];
					
			en[node_a].erase(old_node);
			en[random_mate].insert(node_a);
			en[old_node].erase(node_a);

										
			deque <int> not_common;
			for (set<int>::iterator it_est=en[random_mate].begin(); it_est!=en[random_mate].end(); it_est++)
				if ((old_node!=(*it_est)) && (en[old_node].find(*it_est)==en[old_node].end()))
					not_common.push_back(*it_est);
					
						
			int node_h=not_common[irand(not_common.size()-1)];
			
			en[random_mate].erase(node_h);
			en[node_h].erase(random_mate);
			en[node_h].insert(old_node);
			en[old_node].insert(node_h);
			
			
		}
		
		
	}

	
	
	// now I try to insert the new links into the already done network. If some multiple links come out, I try to rewire them
	
	deque < pair<int, int> > multiple_edge;
	for (int i=0; i<en.size(); i++) {
		
		for(set<int>::iterator its=en[i].begin(); its!=en[i].end(); its++) if(i<*its ) {
		
			bool already = !(E[nodes[i]].insert(nodes[*its]).second);		// true is the insertion didn't take place
			if (already)
				multiple_edge.push_back(make_pair(nodes[i], nodes[*its]));			
			else
				E[nodes[*its]].insert(nodes[i]);
			
		
		}
	
	
	}
	
	
	//cout<<"multiples "<<multiple_edge.size()<<endl;
	for (int i=0; i<multiple_edge.size(); i++) {
		
		
		int &a = multiple_edge[i].first;
		int &b = multiple_edge[i].second;
		
	
		// now, I'll try to rewire this multiple link among the nodes stored in nodes.
		int stopper_ml=0;
		
		while (true) {
					
			stopper_ml++;
			
			int random_mate=nodes[irand(degrees.size()-1)];
			while (random_mate==a || random_mate==b)
				random_mate=nodes[irand(degrees.size()-1)];
			
			if(E[a].find(random_mate)==E[a].end()) {
				
				deque <int> not_common;
				for (set<int>::iterator it_est=E[random_mate].begin(); it_est!=E[random_mate].end(); it_est++)
					if ((b!=(*it_est)) && (E[b].find(*it_est)==E[b].end()) && (binary_search(nodes.begin(), nodes.end(), *it_est)))
						not_common.push_back(*it_est);
				
				if(not_common.size()>0) {
				
					int node_h=not_common[irand(not_common.size()-1)];
					
					
					
					E[random_mate].insert(a);
					E[random_mate].erase(node_h);
					
					E[node_h].erase(random_mate);
					E[node_h].insert(b);
					
					E[b].insert(node_h);
					E[a].insert(random_mate);
					
					break;

				
			
				}
			
			}
			
			if(stopper_ml==2*E.size()) {
	
				cout<<"sorry, I need to change the degree distribution a little bit (one less link)"<<endl;
				break;
	
			}
			
			
			
		}
	
	
	}
	
	


	
	
	return 0;

}
Exemplo n.º 10
0
/*Rotate
 *accessor that returns suggestions
 */
vector<int> Cluster::Rotate(vector<int> L, vector<int> S, int C, int num_results) {

/*might have to make C a list if we are subclustering */    
  vector<int> id_list;
  int current_cluster = C % cluster_map.size();

  sort(S.begin(), S.end() );
  sort(L.begin(), L.end() );

  vector<int> Scopy;

  if(! S.empty()) {
    //see cluster.h - toggle true for random results, default false
    if (! RANDOM) {
      Scopy = S;
      vector<int>::iterator u = unique(Scopy.begin(), Scopy.end());
      Scopy.resize( u - Scopy.begin() );
    }
  }

  //S print
  cout <<"Items Seen:";
  for(vector<int>::iterator it = Scopy.begin(); it != Scopy.end(); ++it) {
    cout << *it << ", ";
  }
  cout <<endl;


  while( id_list.size() < num_results) {
    int result;
    //keep looping - if no results in cluster, we'll switch to another
    //and calculate similarity there
    while ( (result = _calc_Next(L, Scopy, current_cluster, lambda)) == 0 ) {    
      current_cluster = (current_cluster + 1) % cluster_map.size();
    }


    if (! binary_search(Scopy.begin(), Scopy.end(), result) ) {
      /*
       *To retrieve random results,
       *we erase the "memory" of previously seen items
       *inorder for them to be randomly generated.
       */

      if(! RANDOM) {
	Scopy.push_back(result);
      }
      sort(Scopy.begin(), Scopy.end());

      id_list.push_back( result );

      sort(id_list.begin(), id_list.end());
      cout << "doc: " << result <<endl;
      vector<int>::iterator u = unique(Scopy.begin(), Scopy.end());
      Scopy.resize( u - Scopy.begin() );

    }

    current_cluster = (current_cluster + 1) % cluster_map.size();
  }

  return id_list;
}
Exemplo n.º 11
0
/*
 *NOTE: MMR Functions VERY POORLY, SWITHCED TO REGULAR SIMILARITY
 *returns id of highest ranking item, given MMR calculation
 *based on Carbonell, Goldstein, "The Use of MMR, Diversity-Based Reranking
 *for Reordering Documetns and PRoducing Summaries
 */
int Cluster:: _calc_Next (vector<int> L, vector<int> S, int cluster_id, double lambda) {
  //per item in L
  vector<id_sim> id_list;


  //bootstrap; return random in cluster first start
  if ( S.empty() ) {
    cout << "Random: cluster: " << cluster_id <<endl;

    //generate random item in cluster
    srand( time(NULL) );
    int item = rand() % cluster_map[ cluster_id ].size();

    //return the item
    int count = 0;
    for (boost::unordered_set<int>::iterator it = cluster_map[ cluster_id ].begin(); it != cluster_map[ cluster_id ].end(); ++it) {      
      if (count == item) {
	return *it;
      }
      count++;
    }

  }


  if (L.empty()) {
    cout << "Nothing Liked: cluster: " << cluster_id <<endl;

    //MMR Comparison
    if (MMR) {
      cout <<"\t using MMR" <<endl;
      //foreach doc
      for(unordered_int_string_map::iterator it = doc_term_index.begin(); it != doc_term_index.end(); ++it) {
        id_sim item;
        item.id2 = it->first;

	item.sim =  - ( (1 - lambda) * _sum_id_sim_vec( _calc_sim_list(it->first, S) ) / S.size() ) ;
	  
        if ( ! binary_search(S.begin(), S.end(), item.id2)  ) {
          _insert_sorted(id_list, item);
        }
      }

      //test output
      /*
      for(vector<id_sim>::iterator it = id_list.begin(); it != id_list.end(); ++it) {
	cout << "id: " << (*it).id2 << " score: " << (*it).sim <<endl;
      }
      */
      if( id_list.size() <= 0) {
	cout << "Empty List" <<endl;
	return 0;
      }
      //cout <<"id: " << id_list[0].id2 << " score: ";
      //printf("%.20f \n", id_list[0].sim);
      return id_list[0].id2;

    }



    //CLUSTER COMPARISON
    //for items in cluster, find the most dissimilar to ones we have seen before
    for (boost::unordered_set<int>::iterator it = cluster_map[ cluster_id ].begin(); it != cluster_map[ cluster_id ].end(); ++it) {

      //of the similar, lets invert to find most dis_similar of what's already been seen among the cluster
      id_sim sims;
      sims.id2 = *it;
      sims.sim = -  _sum_id_sim_vec(_calc_sim_list( *it, S) );


      if ( ! binary_search(S.begin(), S.end(), sims.id2) ) {
	_insert_sorted(id_list, sims);
      }
    
    }//end loop


  }//end if L.empty()

  else {
    cout <<"Something liked: cluster: " << cluster_id <<endl;
    //among each liked object - get a ranked list the item most "similarly novel"

    //among the liked, rank the centroids
    //stores a list of centroid id, and their similarity values to "liked" items
    vector<id_sim> ranked_centroids;  

    int i =0;
    //foreach liked item
    for (vector<int>::iterator it = L.begin(); it != L.end(); ++it) {

      //rank the centroids in order to that liked item
      vector<id_sim> centroid = _sim_centroids( *it);

      //keep a running sum of the score of each centroids
      ranked_centroids = _merge_ranked_centroids(ranked_centroids, centroid);

    }


    //AT THIS STAGE WE HAVE RANKED LIST OF SIMILAR CENTROIDS (thus clusters)

    //for the best cluster (loop through clusters in case there are too few elements in that particular cluster)
    for (vector<id_sim>::iterator it = ranked_centroids.begin(); it != ranked_centroids.end(); ++it) {

      //for each element in a particular cluster
      for (boost::unordered_set<int>::iterator is = cluster_map[(*it).id2].begin(); is != cluster_map[(*it).id2].end(); ++is) {

	//SIMILARITY METHODOLOGY HERE
	id_sim item;
	item.id2 = *is;
	//item.sim = _sum_id_sim_vec( _calc_sim_list(*is, L) ) - _sum_id_sim_vec( _calc_sim_list(*is, S) );
	//item.sim = lambda * ( _sum_id_sim_vec( _calc_sim_list(*is, L) ) / L.size() ) - ( (1 - lambda) * _sum_id_sim_vec( _calc_sim_list(*is, S) ) / S.size() ) ;
	//item.sim = lambda * _sum_id_sim_vec( _calc_sim_list(*is, L) );

	item.sim =_sum_id_sim_vec( _calc_sim_list(*is, L) );

	if ( ! (binary_search(L.begin(), L.end(), item.id2) ||  binary_search(S.begin(), S.end(), item.id2) ) ) {
	  _insert_sorted(id_list, item);	  
	}	

      }

    }


      
  } //end something liked MMR


  //return 0 if we couldn't find one (indicates move to another cluster
  if( id_list.empty() ) {
    //cout <<"Empty result set, moving clusters"<<endl;
    return 0;
  }
  return id_list[0].id2;
}
Exemplo n.º 12
0
/* monthly - lets the player choose a special edition for the guardian */
int choosespecialedition(char &clearformess)
{
   //Temporary, maybe put special edition definition into an xml file. -XML
	static const string document_types[] =
	{  // This list MUST be in alphabetical order for binary_search() to work right
      "LOOT_AMRADIOFILES",
      "LOOT_CABLENEWSFILES",
      "LOOT_CCS_BACKERLIST",
      "LOOT_CEOLOVELETTERS",
      "LOOT_CEOPHOTOS",
      "LOOT_CEOTAXPAPERS",
      "LOOT_CORPFILES",
      "LOOT_INTHQDISK",
      "LOOT_JUDGEFILES",
      "LOOT_POLICERECORDS",
      "LOOT_PRISONFILES",
      "LOOT_RESEARCHFILES",
      "LOOT_SECRETDOCUMENTS"
	};
	static const vector<string> dox(document_types,document_types+len(document_types));

   int page=0;

   //char havetype[LOOTNUM];
   //for(int l=0;l<LOOTNUM;l++)havetype[l]=0;
   vector<bool> havetype(len(loottype),false);
   vector<int> loottypeindex;

   //FIND ALL LOOT TYPES
   for(int loc=0;loc<len(location);loc++)
   {
      if(location[loc]->renting==RENTING_NOCONTROL) continue;

      consolidateloot(location[loc]->loot);
      for(int l=0;l<len(location[loc]->loot);l++)
      {
         if(!location[loc]->loot[l]->is_loot()) continue;
         if(!binary_search(dox.begin(),dox.end(),location[loc]->loot[l]->get_itemtypename())) continue;

         if(!havetype[getloottype(location[loc]->loot[l]->get_itemtypename())])
         {
            loottypeindex.push_back(getloottype(location[loc]->loot[l]->get_itemtypename()));
            havetype[getloottype(location[loc]->loot[l]->get_itemtypename())]=true;
         }
      }
   }
   for(int sq=0;sq<len(squad);sq++)
   {
      consolidateloot(squad[sq]->loot);
      for(int l=0;l<len(squad[sq]->loot);l++)
      {
         if(!squad[sq]->loot[l]->is_loot()) continue;
         if(!binary_search(dox.begin(),dox.end(),squad[sq]->loot[l]->get_itemtypename())) continue;

         if(!havetype[getloottype(squad[sq]->loot[l]->get_itemtypename())])
         {
            loottypeindex.push_back(getloottype(squad[sq]->loot[l]->get_itemtypename()));
            havetype[getloottype(squad[sq]->loot[l]->get_itemtypename())]=true;
         }
      }
   }

   if(!len(loottypeindex)) return -1;

   clearformess=1;

   //PICK ONE
   while(true)
   {
      music.play(MUSIC_NEWSPAPER);
      erase();

      set_color(COLOR_WHITE,COLOR_BLACK,0);
      move(0,0);
      addstr("Do you want to run a special edition?");

      int x=1,y=10;
      char str[200];

      for(int l=page*18;l<len(loottypeindex)&&l<page*18+18;l++)
      {
         str[0]=l-page*18+'A';
         str[1]='\x0';
         strcat(str," - ");
         strcat(str,loottype[loottypeindex[l]]->get_name());

         move(y,x);
         addstr(str);

         x+=26;
         if(x>53) x=1,y++;
      }

      //PAGE UP
      if(page>0)
      {
         move(17,1);
         addprevpagestr();
      }
      //PAGE DOWN
      if((page+1)*18<len(loottype))
      {
         move(17,53);
         addnextpagestr();
      }

      move(24,1);
      addstr("Enter - Not in this month's Liberal Guardian");

      int c=getkey();

      if(c>='a'&&c<='r')
      {
         int slot=c-'a'+page*18;

         if(slot>=0&&slot<len(loottypeindex))
         {
            //DELETE THE ITEM
            for(int loc=0;loc<len(location);loc++)
            {
               if(location[loc]->renting==RENTING_NOCONTROL) continue;

               for(int l=0;l<len(location[loc]->loot);l++)
               {
                  if(!location[loc]->loot[l]->is_loot()) continue;

                  if(getloottype(location[loc]->loot[l]->get_itemtypename())==loottypeindex[slot])
                  {
                     location[loc]->loot[l]->decrease_number(1);
                     if(location[loc]->loot[l]->empty())
                     	delete_and_remove(location[loc]->loot,l);
                     return loottypeindex[slot];
                  }
               }
            }
            for(int sq=0;sq<len(squad);sq++)
            {
               for(int l=0;l<len(squad[sq]->loot);l++)
               {
                  if(!squad[sq]->loot[l]->is_loot()) continue;

                  if(getloottype(squad[sq]->loot[l]->get_itemtypename())==loottypeindex[slot])
                  {
                     squad[sq]->loot[l]->decrease_number(1);
                     if(squad[sq]->loot[l]->empty())
                        delete_and_remove(squad[sq]->loot,l);
                     return loottypeindex[slot];
                  }
               }
            }

            //WHOOPS!
            return loottypeindex[slot];
         }
      }

      if(c=='x'||c==ENTER||c==ESC||c==SPACEBAR) return -1;

      //PAGE UP
      if((c==interface_pgup||c==KEY_UP||c==KEY_LEFT)&&page>0) page--;
      //PAGE DOWN
      if((c==interface_pgdn||c==KEY_DOWN||c==KEY_RIGHT)&&(page+1)*18<len(loottype)) page++;

   }

   return -1;
}
 int search(vector<int>& nums, int target) {
     return binary_search(nums, 0, nums.size() - 1, target);
 }
Exemplo n.º 14
0
int main()
{
  int n, m, k[MAX_N];

  FILE *fp;

  if((fp = fopen("prob001.in", "r")) == NULL){
    printf("file open error");
    return 1;
  }

  fscanf(fp, "%d %d", &n, &m);
  for(int i = 0; i < n; i++){
    fscanf(fp, "%d", &k[i]);
  }

  fclose(fp);
  
  bool f = false;

  bubble_sort(k, n);

  for(int a = 0; a < n; a++){
    for(int b = 0; b < n; b++){
      for(int c = 0; c < n; c++){
	if(binary_search(m - k[a] - k[b] - k[c], n, k)){
	  f = true;
	}
      }
    }
  }

  if(f) puts("Yes");
  else puts("No");


  /*
  scanf("%d %d", &n, &m);
  for(int i = 0; i < n; i++)
    scanf("%d", &k[i]);
  */

  /*
  bool f = false;

  for(int a = 0; a < n; a++){
    for(int b = 0; b < n; b++){
      for(int c = 0; c < n; c++){
	for(int d = 0; d < n; d++){
	  if(k[a] + k[b] + k[c] + k[d] == m){
	    f = true;
	    printf("%d %d %d %d \n", k[a], k[b], k[c], k[d]);
	  }
	}
      }
    }
  }

  if(f) puts("Yes");
  else puts("No");
  */ 
  return 0;
}
Exemplo n.º 15
0
/* Searches ARRAY, which contains CNT elements of SIZE bytes
   each, for the given KEY.  Returns a match is found, otherwise
   a null pointer.  If there are multiple matches, returns an
   arbitrary one of them.

   ARRAY must be sorted in order according to COMPARE.

   Uses COMPARE to compare elements.  When COMPARE is passed a
   pair of elements A and B, respectively, it must return a
   strcmp()-type result, i.e. less than zero if A < B, zero if A
   == B, greater than zero if A > B. */
void *
bsearch (const void *key, const void *array, size_t cnt,
         size_t size, int (*compare) (const void *, const void *)) 
{
  return binary_search (key, array, cnt, size, compare_thunk, &compare);
}
Exemplo n.º 16
0
bool ItemList::IsItem (string &sItem)
{
	return binary_search (ItemVec.begin(), ItemVec.end(), sItem);
}
Exemplo n.º 17
0
Arquivo: bs.c Projeto: tracer-x/tracer
main()
{
	binary_search(8);
}
Exemplo n.º 18
0
bool search(int value, int lenght, int numbers[])
{
    return binary_search(0, lenght, value, numbers);
}
 void run_query_q5(int author)
 {
     // get docs for authors
     rle_tuple* author_rle_tuple = binary_search(t_docs_per_author_authors, 0, input::A_PM, author);
     int* authors_per_doc_counter = new int[input::D_PM];
     int* docs_per_author = new int[author_rle_tuple->length];
     for (int i = 0; i < author_rle_tuple->length; ++i)
     {
         docs_per_author[i] = t_docs_per_author[i + author_rle_tuple->row_id];
     }
     for (int i = 0; i < author_rle_tuple->length; ++i)
     {
         authors_per_doc_counter[docs_per_author[i]]++;
     }
     delete[] docs_per_author;
     
     // get #docs per term(s)
     // generate arrays, then aggregate arrays
     int* docs_per_term_counter = new int[input::T_PM]();
     int** terms_per_doc = new int*[input::D_PM];
     int* terms_per_doc_length = new int[input::D_PM];
     for (int doc = 0; doc < input::D_PM; ++doc)
     {
         if (authors_per_doc_counter[doc] > 0)
         {
             rle_tuple* doc_rle_tuple = binary_search(t_terms_per_doc_docs, 0, input::D_PM, doc);
             terms_per_doc[doc] = new int[doc_rle_tuple->length];
             for (int j = 0; j < doc_rle_tuple->length; ++j)
             {
                 terms_per_doc[doc][j] = t_terms_per_doc[j + doc_rle_tuple->row_id];
             }
             terms_per_doc_length[doc] = doc_rle_tuple->length;
         }
         else
         {
             terms_per_doc[doc] = NULL;
         }
     }
     
     for (int doc = 0; doc < input::D_PM; ++doc)
     {
         if (terms_per_doc[doc] != NULL)
         {
             for (int j = 0; j < terms_per_doc_length[doc]; ++j)
             {
                 docs_per_term_counter[terms_per_doc[doc][j]] += authors_per_doc_counter[doc];
             }
             delete[] terms_per_doc[doc];
         }
     }
     delete[] terms_per_doc;
     delete[] terms_per_doc_length;
     
     /*
     // get #terms per doc(s)
     int* terms_per_doc_counter = new int[input::D_PM]();
     for (int term = 0; term < input::T_PM; ++term)
     {
         if (docs_per_term_counter[term] > 0)
         {
             // go terms->docs
             rle_tuple* term_rle_tuple = binary_search(t_docs_per_term_terms, 0, input::T_PM, term);
             int* docs_per_term_row_ids = new int[term_rle_tuple->length];
             for (int j = 0; j < term_rle_tuple->length; ++j)
             {
                 docs_per_term_row_ids[j] = j + term_rle_tuple->row_id;
             }
             int* docs_per_term = new int[term_rle_tuple->length];
             for (int j = 0; j < term_rle_tuple->length; ++j)
             {
                 docs_per_term[j] = t_docs_per_term[docs_per_term_row_ids[j]];
             }
             delete[] docs_per_term_row_ids;
             for (int j = 0; j < term_rle_tuple->length; ++j)
             {
                 terms_per_doc_counter[docs_per_term[j]] += docs_per_term_counter[term];
             }
             delete[] docs_per_term;
         }
     }
     delete[] docs_per_term_counter;
     
     // get #docs per author
     int* docs_per_author_counter = new int[input::A_PM]();
     for (int doc = 0; doc < input::D_PM; ++doc)
     {
         if (terms_per_doc_counter[doc] > 0)
         {
             rle_tuple* doc_rle_tuple = binary_search(t_authors_per_doc_docs, 0, input::D_PM, doc);
             int* authors_per_doc_row_ids = new int[doc_rle_tuple->length];
             for (int j = 0; j < doc_rle_tuple->length; ++j)
             {
                 authors_per_doc_row_ids[j] = j + doc_rle_tuple->row_id;
             }
             int* authors_per_doc = new int[doc_rle_tuple->length];
             for (int j = 0; j < doc_rle_tuple->length; ++j)
             {
                 authors_per_doc[j] = t_authors_per_doc[authors_per_doc_row_ids[j]];
             }
             delete[] authors_per_doc_row_ids;
             for (int j = 0; j < doc_rle_tuple->length; ++j)
             {
                 docs_per_author_counter[authors_per_doc[j]] += terms_per_doc_counter[doc];
             }
             delete[] authors_per_doc;
         }
     }
     delete[] terms_per_doc_counter;
      */
     
     int* terms_per_doc_counter = new int[input::D_PM]();
     int next_thread = 0;
     struct thread_data* targs = new struct thread_data[NUM_THREADS];
     pthread_t* threads = new pthread_t[NUM_THREADS]();
     for (int i = 0; i < NUM_THREADS; ++i)
     {
         targs[i].items = new int[input::T_PM];
         targs[i].num_items = 0;
         targs[i].previous_counter_array = docs_per_term_counter;
         targs[i].target_array = terms_per_doc_counter;
     }
     for (int term = 0; term < input::T_PM; ++term)
     {
         if (docs_per_term_counter[term] > 0)
         {
             targs[next_thread].items[targs[next_thread].num_items++] = term;
             next_thread = (next_thread + 1) % NUM_THREADS;
         }
     }
     
     for (int i = 0; i < NUM_THREADS; ++i)
     {
         pthread_create(threads + i, NULL, pthread_step3, (void*) (targs + i));
     }
     for (int i = 0; i < NUM_THREADS; ++i)
     {
         pthread_join(*(threads + i), NULL);
         delete[] targs[i].items;
     }
     delete[] docs_per_term_counter;
     
     int checksum = 0;
     int* docs_per_author_counter = new int[input::A_PM]();
     next_thread = 0;
     threads = new pthread_t[NUM_THREADS]();
     for (int i = 0; i < NUM_THREADS; ++i)
     {
         targs[i].items = new int[input::D_PM];
         targs[i].num_items = 0;
         targs[i].previous_counter_array = terms_per_doc_counter;
         targs[i].target_array = docs_per_author_counter;
     }
     for (int doc = 0; doc < input::D_PM; ++doc)
     {
         if (terms_per_doc_counter[doc] > 0)
         {
             targs[next_thread].items[targs[next_thread].num_items++] = doc;
             next_thread = (next_thread + 1) % NUM_THREADS;
         }
     }
     
     for (int i = 0; i < NUM_THREADS; ++i)
     {
         pthread_create(threads + i, NULL, pthread_step4, (void*) (targs + i));
     }
     for (int i = 0; i < NUM_THREADS; ++i)
     {
         pthread_join(*(threads + i), NULL);
         delete[] targs[i].items;
     }
     delete[] terms_per_doc_counter;
 }
bool is_elem(const vector<int> &vec, const int &value) {

  return binary_search(vec.begin(), vec.end(), value);
}
Exemplo n.º 21
0
int
main(int argc, char **argv)
{
    argc = 0;
	argv = NULL;

	int i = 0;
	int found = 0;
    /* test set funtionality */
    uint64_t array1[len] = {3,4,7,8,10,13,15,23,27,30};
	uint64_t array2[len] = {1,2,3,6,13,30,41,55,66,70};
	
    /* test linear search */
    while(i!=len)
    {
        if((linear_search(array1, len, array2[i]))==9)
        {
            printf("[LINEAR SEARCH] - Search last entry  - OK\n");
        }

	    if((linear_search(array1, len, array2[i]))==0)
		{
		    printf("[LINEAR SEARCH] - Search first entry - OK\n");
		}
		
		if((linear_search(array1, len, array2[i]))==5)
		{
		    printf("[LINEAR SEARCH] - Search middle entry - OK\n");
		}
		
		if((linear_search(array1, len, 31))!=-1)
		{
		    found = 1;
		}
		
        i++;
    }
	
	if(found == 0)
	{
	    printf("[LINEAR SEARCH] - Search larger entry - OK\n\n");
	}
	
    /* test binary search */
	/* Refresh counters */
	i = 0;
	found = 0;
    while(i!=len)
    {
        if((binary_search(array1, len, array2[i]))==9)
        {
            printf("[BINARY SEARCH] - Search last entry  - OK\n");
        }

	    if((binary_search(array1, len, array2[i]))==0)
		{
		    printf("[BINARY SEARCH] - Search first entry - OK\n");
		}
		
		if((binary_search(array1, len, array2[i]))==5)
		{
		    printf("[BINARY SEARCH] - Search middle entry - OK\n");
		}
		
		if((binary_search(array1, len, 31))!=-1)
		{
		    found = 1;
		}
		
        i++;
    }
	
	if(found == 0)
	{
	    printf("[BINARY SEARCH] - Search larger entry - OK\n\n");
	}
	
    /* test interpolation search */
    /* Refresh counters */
	i = 0;
	found = 0;
    while(i!=len)
    {
        if((interpolation_search(array1, len, array2[i]))==9)
        {
            printf("[INTERPOLATION SEARCH] - Search last entry  - OK\n");
        }

	    if((interpolation_search(array1, len, array2[i]))==0)
		{
		    printf("[INTERPOLATION SEARCH] - Search first entry - OK\n");
		}
		
		if((interpolation_search(array1, len, array2[i]))==5)
		{
		    printf("[INTERPOLATION SEARCH] - Search middle entry - OK\n");
		}
		
		if((interpolation_search(array1, len, 31))!=-1)
		{
		    found = 1;
		}
		
        i++;
    }
	
	if(found == 0)
	{
	    printf("[INTERPOLATION SEARCH] - Search larger entry - OK\n\n");
	}
	
    /* test exponential search */
    /* Refresh counters */
	i = 0;
	found = 0;
    while(i!=len)
    {
        if((exponential_search(array1, len, array2[i]))==9)
        {
            printf("[EXPONENTIAL SEARCH] - Search last entry  - OK\n");
        }

	    if((exponential_search(array1, len, array2[i]))==0)
		{
		    printf("[EXPONENTIAL SEARCH] - Search first entry - OK\n");
		}
		
		if((exponential_search(array1, len, array2[i]))==5)
		{
		    printf("[EXPONENTIAL SEARCH] - Search middle entry - OK\n");
		}
		
		if((exponential_search(array1, len, 31))!=-1)
		{
		    found = 1;
		}
		
        i++;
    }
	
	if(found == 0)
	{
	    printf("[EXPONENTIAL SEARCH] - Search larger entry - OK\n\n");
	}
	
    /* test block search */
    /* Refresh counters */
	i = 0;
	found = 0;
    while(i!=len)
    {
        if((block_search(array1, len, array2[i], bsize))==9)
        {
            printf("[BLOCK SEARCH] - Search last entry  - OK\n");
        }

	    if((block_search(array1, len, array2[i], bsize))==0)
		{
		    printf("[BLOCK SEARCH] - Search first entry - OK\n");
		}
		
		if((block_search(array1, len, array2[i], bsize))==5)
		{
		    printf("[BLOCK SEARCH] - Search middle entry - OK\n");
		}
		
		if((block_search(array1, len, 31, bsize))!=-1)
		{
		    found = 1;
		}
		
        i++;
    }
	
	if(found == 0)
	{
	    printf("[BLOCK SEARCH] - Search larger entry - OK\n\n");
	}
	
	return EXIT_SUCCESS;
}
Exemplo n.º 22
0
int main() {
    int int_array[5] = {1, 3, 5, 7, 8};
    printf("%d\n", binary_search(5, int_array, sizeof int_array / sizeof *int_array) );

    return EXIT_SUCCESS;
}
Exemplo n.º 23
0
bool USB_DA12_8E_Family::isSupportedProductID( int productID ) {
	initialize();
	return binary_search( supportedProductIDs.begin(), supportedProductIDs.end(), productID );
}	// USB_DA12_8E_Family::isSupportedProductID()
Exemplo n.º 24
0
bool search(vector<T> v,T t) {
    bool answer =  binary_search(v.begin(),v.end(),t);
    return answer;
}
Exemplo n.º 25
0
/* This function is REALLY HOT. It gets called for every file */
int filename_filter(const wchar_t *path, const struct dirent *dir, void *baton) {
	const wchar_t *filename = dir->d_name;
/* TODO: don't call strlen on filename every time we call filename_filter() */
#ifdef HAVE_DIRENT_DNAMLEN
    size_t filename_len = dir->d_namlen;
#else
    size_t filename_len = wcslen(filename);
#endif
    size_t i;
    scandir_baton_t *scandir_baton = (scandir_baton_t *)baton;
    const ignores *ig = scandir_baton->ig;
	const wchar_t *base_path = scandir_baton->base_path;
    const size_t base_path_len = scandir_baton->base_path_len;
	const wchar_t *path_start = path;
    wchar_t *temp;

    if (!opts.search_hidden_files && filename[0] == '.') {
        return 0;
    }

    for (i = 0; evil_hardcoded_ignore_files[i] != NULL; i++) {
        if (wcscmp(filename, evil_hardcoded_ignore_files[i]) == 0) {
            return 0;
        }
    }

    if (!opts.follow_symlinks && is_symlink(path, dir)) {
        log_debug(L"File %s ignored becaused it's a symlink", dir->d_name);
        return 0;
    }

    if (is_named_pipe(path, dir)) {
        log_debug(L"%s ignored because it's a named pipe", path);
        return 0;
    }

    if (opts.search_all_files && !opts.path_to_agignore) {
        return 1;
    }

    for (i = 0; base_path[i] == path[i] && i < base_path_len; i++) {
        /* base_path always ends with "/\0" while path doesn't, so this is safe */
        path_start = path + i + 2;
    }
    log_debug(L"path_start %s filename %s", path_start, filename);

    const wchar_t *extension = wcsrchr(filename, '.');
    if (extension) {
        if (extension[1]) {
            // The dot is not the last character, extension starts at the next one
            ++extension;
        } else {
            // No extension
            extension = NULL;
        }
    }

     while (ig != NULL) {
        if (wcsncmp(filename, L"./", 2) == 0) {
            filename++;
            filename_len--;
        }

        if (extension) {
            int match_pos = binary_search(extension, ig->extensions, 0, ig->extensions_len);
            if (match_pos >= 0) {
                log_debug(L"file %s ignored because name matches extension %s", filename, ig->extensions[match_pos]);
                return 0;
            }
        }

        if (path_ignore_search(ig, path_start, filename)) {
            return 0;
        }

        if (is_directory(path, dir) && filename[filename_len - 1] != '/') {
            ag_asprintf(&temp, L"%s/", filename);
            int rv = path_ignore_search(ig, path_start, temp);
            free(temp);
            if (rv) {
                return 0;
            }
        }
        ig = ig->parent;
    }

    log_debug(L"%s not ignored", filename);
    return 1;
}
Exemplo n.º 26
0
// To execute C, please define "int main()"
  int a[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,16};
  int len = sizeof(a)/sizeof(int);
  int i;
  
    printf("-1 VS %d\n", binary_search(a, len, 0));
    printf("9 VS %d\n", binary_search(a, len, 10));
    printf("10 VS %d\n", binary_search(a, len, 11));
    printf("14 VS %d\n", binary_search(a, len, 16));
    printf("-1 VS %d\n", binary_search(a, len, -1));
    printf("-1 VS %d\n", binary_search(a, len, 18));
  printf("End\n");

void swap(int *a, int *b)
{
  int temp;
  temp = *a;
  *a = *b;
  *b = temp;
}
void bubble_sort(int *a, int len)
{
  int i, j;
  int orderd = 1;
  
  if (len <= 0 || !a)
    return;
  for (i = len-1; i>= 0; i--) {
    orderd = 1;
    for (j = 0; j < i; j++) {
      if (a[j] > a[j+1]) {
Exemplo n.º 27
0
bool ListDuplicateCS (std::wostream& listStrm)
{
	bool ok (false);
	int st;
	unsigned dupCount;
	unsigned long epsgCodeII;
	unsigned long epsgCodeJJ;
	const cs_Csdef_ *csPtrII;
	const cs_Csdef_ *csPtrJJ;
	double qValue;
	char message [1024];

	std::vector<TcsKeyName> duplicateNameVector;
	std::vector<TcsKeyNameList> duplicateListVector;
	std::vector<TcsKeyNameList>::iterator itrDuplicateListVctr;

	TcsCoordsysFile csFile;
	if (csFile.IsOk ())
	{
		size_t ii, jj, csCount;
		csCount = csFile.GetRecordCount ();
		duplicateNameVector.clear ();
		duplicateNameVector.reserve (1024);

		for (ii = 0;ii < (csCount - 1);ii +=1 )
		{
			csPtrII = csFile.FetchCoordinateSystem (ii);
			if (csPtrII == 0) break;
			if (!CS_stricmp (csPtrII->group,"LEGACY")) continue;
			if (!CS_stricmp (csPtrII->prj_knm,"LM-WCCS")) continue;
			if (!CS_stricmp (csPtrII->prj_knm,"LM-MNDOT")) continue;
			if (!CS_stricmp (csPtrII->prj_knm,"TM-WCCS")) continue;
			if (!CS_stricmp (csPtrII->prj_knm,"TM-MNDOT")) continue;
			epsgCodeII = csMapNameToIdC (csMapProjGeoCSys,csMapFlvrEpsg,csMapFlvrAutodesk,csPtrII->key_nm);

			TcsKeyName primaryName (csKyNmTypeCRS,csPtrII->key_nm,epsgCodeII);
			primaryName.SetQuality (csPtrII);
			TcsKeyNameList duplicateList (primaryName);
			dupCount = 0;

			// If this coordinate system name already appears in our duplicate
			// name vector, we ignore it.  It's already a secondary name and we
			// don't want it to appear as also as a primary name.
			if (binary_search (duplicateNameVector.begin (),duplicateNameVector.end (),primaryName))
			{
				continue;
			}

			for (jj = (ii + 1);jj < csCount;jj += 1)
			{
				csPtrJJ = csFile.FetchCoordinateSystem (jj);
				if (csPtrJJ == 0) break;
				if (!CS_stricmp (csPtrJJ->group,"LEGACY")) continue;
				if (!CS_stricmp (csPtrJJ->prj_knm,"LM-WCCS")) continue;
				if (!CS_stricmp (csPtrJJ->prj_knm,"LM-MNDOT")) continue;
				if (!CS_stricmp (csPtrJJ->prj_knm,"TM-WCCS")) continue;
				if (!CS_stricmp (csPtrII->prj_knm,"TM-MNDOT")) continue;
				if (CS_stricmp (csPtrII->dat_knm,csPtrJJ->dat_knm)) continue;
				message [0] = '\0';
				st = CS_csDefCmpEx (&qValue,csPtrII,csPtrJJ,message,sizeof (message));
				if ((st == 0) && (qValue < 3.0))
				{
					dupCount += 1;
					epsgCodeJJ = csMapNameToIdC (csMapProjGeoCSys,csMapFlvrEpsg,csMapFlvrAutodesk,csPtrJJ->key_nm);
					if (epsgCodeJJ == KcsNmInvNumber) epsgCodeJJ = 0UL;
					TcsKeyName duplicateName (csKyNmTypeCRS,csPtrJJ->key_nm,epsgCodeJJ);
					duplicateName.SetQuality (csPtrJJ);
					duplicateNameVector.push_back (duplicateName);
					duplicateList += duplicateName;
				}
			}

			if (dupCount > 0)
			{
				duplicateListVector.push_back (duplicateList);
				std::stable_sort (duplicateNameVector.begin (),duplicateNameVector.end ());
			}
		}

		// OK, we have a vector of TcsKeyNameList objects which represent the definitions
		// which are candidates for drepecation as duplicates.  We do some arranging
		// and print the results out in a form ammenable to inserting as a data object
		// initialization in a C++ source code module.
		for (itrDuplicateListVctr  = duplicateListVector.begin ();
			 itrDuplicateListVctr != duplicateListVector.end ();
			 itrDuplicateListVctr++)
		{
			// Here once for each instance of duplicate deifnitions.  First we
			// "Arrange" the names so the most preferred name is the "Primary" name.
			// Then we write them out in a ofrm suitable for the C++ compiler.
			TcsKeyNameList& keyNameList = *itrDuplicateListVctr;
			keyNameList.Arrange ();
			keyNameList.WriteToStream (listStrm);
		}
		ok = true;
	}
	return ok;
}
Exemplo n.º 28
0
NETSNMP_STATIC_INLINE int
netsnmp_binary_array_insert(netsnmp_container *c, const void *entry)
{
    binary_array_table *t = (binary_array_table*)c->container_data;
    int             new_max;
    int             index = -1; /* append */

    if (t->count == 0)
        ;       /* Trivial case of empty list */
    else if (c->flags & CONTAINER_KEY_UNSORTED) {
        /* Unsorted list, always append but check for dups */
        if ( !(c->flags & CONTAINER_KEY_ALLOW_DUPLICATES) &&
            linear_search(entry, c) != -1)
            goto duplicate;

    } else {
        int last = t->count - 1;
        int result;

        /* Optimize for case of appending to end of array. */
        if ( (result = c->compare(t->data[last], entry)) <= 0) {
            /* and check for duplicate */
            if ( !(c->flags & CONTAINER_KEY_ALLOW_DUPLICATES) &&
                 result == 0)
                goto duplicate;
        } else {
            /* Find nearest match.
             * Returns the index of the entry to put after this one.
             * -1 means put at the end.
             */
            index = binary_search(entry, c, 0);

            /*
             * If key is duplicate then the entry before it
             * will be the same.
             */
            if ( !(c->flags & CONTAINER_KEY_ALLOW_DUPLICATES) &&
                 index > 0 &&
                 c->compare(t->data[index - 1], entry) == 0)
                goto duplicate;
        }
    }

    /*
     * check if we need to resize the array
     */
    if (t->max_size <= t->count) {
        /*
         * Table is full, so extend it to double the size, or use 10 elements
         * if it is empty.
         */
        size_t const new_max = t->max_size > 0 ? 2 * t->max_size : 10;
        void ** const new_data =
            (void**) realloc(t->data, new_max * sizeof(void*));

        if (new_data == NULL)
            return -1;

        t->data = new_data;
        t->max_size = new_max;
    }

    /*
     * Insert the new entry into the data array
     */
    if (index == -1)
        index = t->count;
    else
        memmove(&t->data[index+1], &t->data[index],
                sizeof(void *) * (t->count - index));

    t->data[index] = NETSNMP_REMOVE_CONST(void *, entry);
    t->count++;

    ++c->sync;

    return 0;

duplicate:
    DEBUGMSGTL(("container","not inserting duplicate key\n"));
    return -1;
}
Exemplo n.º 29
0
bool cGuildStone::isMember(P_CHAR pc)
{
	return binary_search(member.begin(), member.end(), pc->serial);
}
void MsInterpolation::build_hierarchy_based_on_face( FaceNode *subroot, int level /*= 0*/ )
{
	FaceNode *curr_node;
	MyFaceHandle curr_face_handle;

	int nr_faces = subroot->idx.size();
	int last_pos[NR_MIN_PATCH_PER_LEVEL];
	
	std::vector<int> face_flag;
	face_flag.assign(nr_faces, -1);

	std::vector<bool> need_iter;
	need_iter.assign(nr_faces, true);

	std::map<int, int> ridx;
	for(int i = 0; i < nr_faces; i++)
	{
		ridx.insert( std::pair<int, int>(subroot->idx[i], i) );
	}

	int seed_idx[NR_MIN_PATCH_PER_LEVEL];
	random_seed_point_helper(nr_faces, seed_idx);

	for(int i = 0; i < NR_MIN_PATCH_PER_LEVEL; i++)
	{
		int selected_idx = seed_idx[ i ];
		curr_node = subroot->next[i] = new FaceNode();

		curr_node->idx.push_back( subroot->idx[ selected_idx ] );
		face_flag[ selected_idx ] = i;

		last_pos[ i ] = 0;//设置起点
	}

	MyMesh::FaceIter face_iter;
	MyMesh::FaceFaceIter faceface_iter;
	MyFaceHandle close_face_handle;

	bool done;

	int start_pos, end_pos;// 定义iterator区间

	while( 1 )
	{
		done = true;
		for(int i = 0; i < nr_faces; i++)
		{
			if( face_flag[ i ] == -1 )
			{
				done = false;
				break;
			}
		}

		if( done )
		{
			break;// 此level结束
		}

		for(int i = 0; i < NR_MIN_PATCH_PER_LEVEL; i++)
		{

			curr_node = subroot->next[ i ];

			start_pos = last_pos[ i ];
			end_pos = curr_node->idx.size();

			for(int j = start_pos; j != end_pos; j++)
			{
				curr_face_handle = MyFaceHandle( curr_node->idx[ j ] );

				if( ! need_iter[ ridx[ curr_face_handle.idx() ] ] )
				{
					continue;
				}

				for( faceface_iter = m_mesh.ff_begin( curr_face_handle ); faceface_iter; ++faceface_iter )
				{
					close_face_handle = faceface_iter.handle();
					int close_idx = close_face_handle.idx();

					int ret = binary_search( subroot->idx.begin(), subroot->idx.end(), close_idx );
					if ( ret == false )
					{
						continue;// 该face不在上一层的patch中
					}

					int used = face_flag[ ridx[ close_idx ] ];
					if( used == -1 )
					{
						// 还未被使用
						curr_node->idx.push_back( close_idx );
						face_flag[ ridx[ close_idx ] ] = i;

					}else
					{
						if( used != i)
						{
							// 邻近patch的三角形
							curr_node->boundray.push_back( close_idx );
						}
					}

				}
				
			}
			last_pos[ i ] = end_pos;

		}

	}


    /*** 添加边缘 ***/
	for (int i = 0; i != NR_MIN_PATCH_PER_LEVEL; i++)
	{

		FaceNode *node_i = subroot->next[i];
		node_i->idx.insert( node_i->idx.end(), node_i->boundray.begin(), node_i->boundray.end() );
	}


	/*** 去重 ***/
	for (int i = 0; i != NR_MIN_PATCH_PER_LEVEL; i++)
	{

		FaceNode *node_i = subroot->next[i];

		sort( node_i->idx.begin(), node_i->idx.end() ); // 排序

		std::vector<int>::iterator iter;

		iter = unique(node_i->idx.begin(), node_i->idx.end() );
		node_i->idx.erase( iter, node_i->idx.end() );
	}

	level++;
	
	for(int i = 0; i < NR_MIN_PATCH_PER_LEVEL; i++)
	{
		int next_idx_len = subroot->next[ i ]->idx.size();
		
		if( next_idx_len < min_size_node )
		{
			min_size_node = next_idx_len;
		}

		if( next_idx_len > LEAF_NODE_MIN_NR )
		{
			build_hierarchy_based_on_face( subroot->next[ i ], level );
		}
	}
}