void Ioss::ParallelUtils::global_count(const IntVector &local_counts, IntVector &global_counts) const { // Vector 'local_counts' contains the number of objects // local to this processor. On exit, global_counts // contains the total number of objects on all processors. // Assumes that ordering is the same on all processors global_counts.resize(local_counts.size()); #ifdef HAVE_MPI if (local_counts.size() > 0 && parallel_size() > 1) { if (Ioss::SerializeIO::isEnabled() && Ioss::SerializeIO::inBarrier()) { std::ostringstream errmsg; errmsg << "Attempting mpi while in barrier owned by " << Ioss::SerializeIO::getOwner(); IOSS_ERROR(errmsg); } const int success = MPI_Allreduce((void*)&local_counts[0], &global_counts[0], static_cast<int>(local_counts.size()), MPI_INT, MPI_SUM, communicator_); if (success != MPI_SUCCESS) { std::ostringstream errmsg; errmsg << "Ioss::ParallelUtils::global_count - MPI_Allreduce failed"; IOSS_ERROR(errmsg); } } else { // Serial run, just copy local to global... std::copy(local_counts.begin(), local_counts.end(), global_counts.begin()); } #else std::copy(local_counts.begin(), local_counts.end(), global_counts.begin()); #endif }
double ImageUtils::estimateLineThickness(Image &bwimg, int grid) { int w = bwimg.getWidth(); int h = bwimg.getHeight(); int d = grid; IntVector lthick; if(w < d) d = std::max<int>(w >>1, 1) ; { int startseg = -1; for(int i = 0; i < w ; i += d) { for(int j = 0; j < h; j++) { byte val = bwimg.getByte(i, j); if(val == 0 && (startseg == -1)) startseg = j; if((val > 0 || j==(h-1)) && startseg != -1) { lthick.push_back(j - startseg + 1); startseg = -1; } } } } if(h > d) d = grid; else d = std::max<int>(h >>1, 1) ; { int startseg = -1; for(int j = 0; j< h; j+=d) { for(int i = 0; i < w; i++) { byte val = bwimg.getByte(i, j); if(val == 0 && (startseg == -1)) startseg = i; if((val > 0 || i==(w-1)) && startseg != -1) { lthick.push_back(i - startseg + 1); startseg = -1; } } } } std::sort(lthick.begin(), lthick.end()); double thickness = 0; if(lthick.size() > 0) thickness = StatUtils::interMean(lthick.begin(), lthick.end()); return thickness; }
void trivialShuffle(IntVector &deck) { int deckSize = deck.size(); int hit = rnd(deckSize); for(IntVector::iterator i = deck.begin(); i != deck.end(); ++i) { if(*i != hit) iter_swap(i, deck.begin() + hit); hit = rnd(deckSize); }; }
size_t most_frequent_run(const T& image, const Color& color, const Direction& direction) { IntVector* hist = run_histogram(image, color, direction); size_t result; try { result = std::max_element(hist->begin(), hist->end()) - hist->begin(); } catch (std::exception e) { delete hist; throw; } delete hist; return result; }
////////////////////////////////////////////////////////////////////// // Constructs the storing key for the integer vector given as // parameter // Most of the efficiency of the memoization table resides here // if this key generation takes too much time then it will // globally slow the algorithm down ////////////////////////////////////////////////////////////////////// string MemoizationLevel::makeKey(IntVector &iv) { ostringstream out; //First sort the vector so that vector with the same entries in different orders //will occupy the same position sort(iv.begin(), iv.end()); //Then converts each component of the vector into the key for(IntVector::iterator i=iv.begin(); i!=iv.end(); i++) { out << intToKey(*i);//<< ","; //The end of these line is only to be used with variable string size } return out.str(); }
void generateBacktrack(IntVector& current_set, unsigned n) { unsigned csum = std::accumulate(current_set.begin(), current_set.end(), 0); if (csum > n) { //discard this solution return; } if (csum == n) //if solution, print it { processSolution(current_set); } else { IntVector candidates = getCandidates(current_set, n, csum); for (unsigned i =0; i < candidates.size(); ++i) { current_set.push_back(candidates.at(i)); generateBacktrack(current_set, n); current_set.pop_back(); } } }
inline void IndexedList::erase(size_t const&e) { // check(); if (contains(e)) { // TRACE("remove "<<e<<" " <<_element[e]<<std::endl); // for (IntVector::const_iterator i(_list.begin()); i != _list.end(); ++i) // std::cout << *i << std::endl; /// on switch avec le dernier puis on réduit // std::cout << "_list[" << _element[e] << "] = " << _list.back() // << std::endl; _list[_element[e]] = front(); _element[front()] = _element[e]; // std::cout << "_element[" << e << "] = " << max_size() << std::endl; _element[e] = max_size(); _list[size() - 1] = -1; // std::cout << "_list[" << size() - 1 << "] = -1;" << std::endl; _list.erase(_list.begin() + _list.size() - 1); // std::cout << "###########" << std::endl; // for (IntVector::const_iterator i(_list.begin()); i != _list.end(); ++i) // std::cout << *i << std::endl; /// } // check(); // TRACE_N(size()); // TRACE_N(max_size()); // DEBUG_ASSERT("NO REALLOCATION ALLOWED"&&size()<=max_size()); }
void print_path(const char *text, const IntVector &path) const { Rprintf("%s:", text); for(IntVector::const_iterator j=path.begin(); j!=path.end(); ++j) Rprintf(" %d", *j); Rprintf("\n"); }
static void addInt(int len) { int i = integers.indexOf(len); // TODO: test this change and refactor it IntVector::Iterator it = i == -1 ? integers.end() : (integers.begin()+i); if (it == integers.end()) { integers.append(len); } }
void printVector(IntVector const& subset) { std::cout<<"{"; for (IntVector::const_iterator vect_it(subset.begin()); vect_it != subset.end(); ++vect_it) { std::cout<<*vect_it<<" "; } std::cout<<"}\n"; }
void processSolution(IntVector const& subset) { if (subset.size() < cmin) { cmin = subset.size(); solution.assign(subset.begin(), subset.end()); } //printVector(subset); }
void runcase() { sort(edgeNums.begin(), edgeNums.end(), edgeComp); int result = INF; for(IntVectorIter minIt = edgeNums.begin(); minIt < edgeNums.end(); minIt++) { int minW = edges[*minIt].weight; int maxW = minW; // 假如it是最小边,求最小生成树 for(int i = 0; i < n; i++) SET[i] = i; for(IntVectorIter it = minIt; it < edgeNums.end(); it++) { const Edge& e = edges[*it]; int x = find(e.from); int y = find(e.to); if(x != y) { SET[x] = y; maxW = e.weight; } } // 要判断最小生成树是否连通了 bool connected = true; for(int i = 0; i < n; i++) if(find(i) != find(0)) { connected = false; break; } if(connected) result = min(result, maxW - minW); } if(result == INF) result = -1; printf("%d\n", result); }
int main () { typedef vector <int> IntVector; IntVector v (10); for (int i = 0; i < v.size (); i++) v[i] = i; IntVector::iterator location = v.begin (); cout << "At Beginning: " << *location << endl; advance (location, 5); cout << "At Beginning + 5: " << *location << endl; return 0; }
unsigned getCoin(unsigned i) { //binary_search if (std::binary_search(coins.begin(), coins.end(), i)) { //std::cout<<"Found exact coin: "<<i<<"\n"; return i; } return 0; }
FileSplit::FileSplit ( const IntVector& nFileSpec, const DoubleVector& prop, int maxSpectra ) { totSpec = accumulate ( nFileSpec.begin (), nFileSpec.end (), 0 ); int maxSpecPerProcess = static_cast<int> ( totSpec * prop [0] ); numSerial = ( maxSpecPerProcess / maxSpectra ) + 1; // Number of serial searches IntVector nSearchSpec; for ( DoubleVectorSizeType i = 0 ; i < prop.size () ; i++ ) { for ( int j = 0 ; j < numSerial ; j++ ) { nSearchSpec.push_back ( static_cast<int> ( ( totSpec / numSerial ) * prop [i] ) ); } } int rem = accumulate ( nSearchSpec.begin (), nSearchSpec.end (), 0 ) - totSpec; while ( rem != 0 ) { int inc = ( rem < 0 ) ? 1 : -1; for ( DoubleVectorSizeType i = 0 ; i < prop.size () ; i++ ) { nSearchSpec [i] += inc; rem += inc; if ( rem == 0 ) break; } } init ( nFileSpec, nSearchSpec ); }
int main(int argc, char* argv[]) { if (argc != 2) { std::cerr<<"Usage: ./coin <number>\n"; return -1; } coins.push_back(1); //coins.push_back(2); //coins.push_back(5); coins.push_back(10); coins.push_back(25); std::sort(coins.begin(), coins.end()); unsigned long number = boost::lexical_cast<unsigned long>(std::string(argv[1])); if (number < 25) { clock_t ticks = clock(); IntVector cset; generateBacktrack(cset, number); printVector(solution); std::cout << "Back: "<< clock() - ticks << std::endl; } { //not working good solution.clear(); computeCoins(number); std::cout<<"Greedy: "; printVector(solution); } if (number < 100) { //another solution //change(n)= 1+ min({change(n-1),change(n-2),change(n-5)}) solution.clear(); unsigned n = computeRecursive(number); std::cout<<"recursive n: "<<n<<"\n"; } { solution.clear(); computeDynamic(number); } return 0; }
void CompressedDataColumn::removeFromColumnVector(IntVector removeEntries){ int lastit = 0; IntVector::iterator it1 = removeEntries.begin(); IntVector::iterator it2 = columns->begin(); while(it1 < removeEntries.end() && it2 < columns->end()){ if(*it1 < *it2) it1++; else if(*it2 < *it1){ it2++; } else{ columns->erase(it2); it2 = columns->begin() + lastit; } } }
inline IntVector* projection(T i, const T end) { IntVector* proj = new IntVector(end - i, 0); try { typename T::iterator j; typename IntVector::iterator p = proj->begin(); for (; i != end; ++i, ++p) { for (j = i.begin(); j != i.end(); ++j) { if (is_black(*j)) *p += 1; } } } catch (std::exception e) { delete proj; throw; } return proj; }
FileSplit::FileSplit ( const IntVector& nFileSpec, int numProcesses, int maxSpectra ) { totSpec = accumulate ( nFileSpec.begin (), nFileSpec.end (), 0 ); int nSpecPerProcess = totSpec / numProcesses; // Number of spectra per process numSerial = ( nSpecPerProcess / maxSpectra ) + 1; // Number of serial searches int numSearches = numProcesses * numSerial; // Number of searches int nSpecPerSearch = totSpec / numSearches; // Number of spectra per search int rem = totSpec % numSearches; IntVector nSearchSpec; for ( int i = 0 ; i < numSearches ; i++ ) { int n = nSpecPerSearch; if ( rem != 0 ) { n += 1; rem--; } nSearchSpec.push_back ( n ); } init ( nFileSpec, nSearchSpec ); }
IntVector DijkstraPlanner::Plan(int start, int goal, const PlanningGraph &graph) const { IntVector path; int num_vertices = graph.num_vertices(); if (start < 0 || start >= num_vertices || goal < 0 || goal >= num_vertices) { throw std::invalid_argument("Invalid vertex id."); } IndexPriorityQueue<double> prique; std::map<int, int> came_from; std::map<int, std::list<EdgeNode*> > adjlist = graph.adjlist(); RealVector dist(graph.num_vertices()); dist[start] = 0.0; for (int i = 0; i < num_vertices; ++i) { if (i != start) { dist[i] = std::numeric_limits<double>::max(); } prique.Push(i, dist[i]); } while (!prique.Empty()) { int current = prique.Pop(); for (std::list<EdgeNode*>::iterator iter = adjlist[current].begin(); iter != adjlist[current].end(); ++iter) { int neighbor = static_cast<PlanningEdgeNode*>(*iter)->target(); double temp_dist = dist[current] + graph.EdgeWeight(current, neighbor); if (temp_dist < dist[neighbor]) { dist[neighbor] = temp_dist; came_from[neighbor] = current; prique.Update(neighbor, dist[neighbor]); } } } int current = goal; path.push_back(current); while (current != start) { current = came_from[current]; path.push_back(current); } std::reverse(path.begin(), path.end()); return path; }
IntVector getNext(unsigned number) { IntVector result; IntVector::const_iterator coin_it(coins.begin()); for (; coin_it != coins.end(); ++coin_it) { if (number >= *coin_it) { result.push_back(number - *coin_it); } else { break; } } return result; }
Path NewMIRAAlgorithm::compute(const Flow &flow) { TRACE("NewMIRAAlgorithm::compute -->"); Topology *topology = flow.getTopology(); const int f_src = flow.getSource(); const int f_dst = flow.getDestination(); // if link (i,j) exists, its metric is initialized with 0 (it increases each // time a maxflow computation is performed) and it is added to the list that // feeds the maxflow function int numarcs = 0; int number_of_nodes = topology->getNumNodes(); // data structure passed to maxflow function char** network = (char**) calloc(4, sizeof(char*)); for (LinkListIterator iter = topology->getLinkIterator(); iter(); ++iter) { Link* link = *iter; if (link->getCapacity() > 0.0) { link->metric = 0.0; ++numarcs; network = (char**) realloc(network, (numarcs+4)*sizeof(char*)); network[numarcs+2] = (char*) calloc(20, sizeof(char)); sprintf(network[numarcs+2],"a %d %d %d", link->getSource(), link->getDestination(), (int) floor(link->getReservableCapacity())); } // end: if (link-> } // end: for (LinkListIterator iter network[0] = (char*) calloc(20, sizeof(char)); // problem description network[1] = (char*) calloc(20, sizeof(char)); // source node network[2] = (char*) calloc(20, sizeof(char)); // destination node network[numarcs+3] = (char*) 0; // NULL terminated array sprintf(network[0],"p max %d %d", number_of_nodes, numarcs); #ifndef NO_TIMER Timer timer; timer.start(); #endif // NO_TIMER // Compute maxflow for each ingress-egress pair except (source,dest). // Each computation updates link weights //Timer timemaxflow; //timemaxflow.start(); //int n = 0; const IntVector edge_nodes = topology->getEdgeNodes(); for (IntVector::const_iterator s_iter = edge_nodes.begin(); s_iter != edge_nodes.end(); ++s_iter) { for (IntVector::const_iterator d_iter = edge_nodes.begin(); d_iter != edge_nodes.end(); ++d_iter) { if (*s_iter != *d_iter && !(f_src == *s_iter && f_dst == *d_iter)) { //PRINTLN("s: " << *s_iter << "\td: " << *d_iter << "\tn: " << n); //n++; // complete network with current ingress-egress pair sprintf(network[1],"n %d s", *s_iter); sprintf(network[2],"n %d t", *d_iter); // needed by maxflow function node *ndp; arc *arp; long *cap; double mflow; long nmin; //compute maxflow //Timer t; //t.start(); maxflow(network,&ndp,&arp,&cap,&mflow,&nmin); //PRINTLN("\tTimer: " << t.read()); // update link weights for (node* in = ndp; in < (ndp + number_of_nodes); ++in) { for (arc* a = in->first; a != 0; a = a->next) { long ni = N_NODE(in); long na = N_ARC(a); if ( cap[na] > 0 ) { Link* link = topology->link(ni, N_NODE(a->head)); link->metric +=(cap[na] - a->r_cap) / (mflow*link->getReservableCapacity()); } // end: if ( cap[na] > 0 ) } // end: for ( arc* } // end: for (node* // free memory free(ndp); free(arp); free(cap); } // end: if ( (source } // end: for (int dest } // end: for (int source //PRINTLN("Timer: " << timemaxflow.read() << "\tn:" << n); // free memory for (int i=0; i<numarcs+3; ++i) { free(network[i]); } free(network); double f_cap = flow.getRequestedCapacity(); // pruning of the links with insufficient bandwidth for (LinkListIterator iter = topology->getLinkIterator(); iter(); ++iter) { if ((*iter)->getReservableCapacity() < f_cap) { (*iter)->metric = -1.0; } } // invoking Dijkstra Path result(routing_alg->compute(flow)); #ifndef NO_TIMER const_cast<Flow&>(flow).setTime(timer.read()); #endif // NO_TIMER TRACE("NewMIRAAlgorithm::compute <--"); return result; }
size_t find1(const IntVector& v) { return find(v.begin(), v.end(), 1) - v.begin(); }
int DesignOfExperiments_Impl::createNextIteration(Analysis& analysis) { int result(0); // to make sure problem type check has already occurred. this is stated usage in header. OS_ASSERT(analysis.algorithm().get() == getPublicObject<DesignOfExperiments>()); // nothing else is supported yet DesignOfExperimentsOptions options = designOfExperimentsOptions(); OS_ASSERT(options.designType() == DesignOfExperimentsType::FullFactorial); if (isComplete()) { LOG(Info,"Algorithm is already marked as complete. Returning without creating new points."); return result; } if (options.maxIter() && options.maxIter().get() < 1) { LOG(Info,"Maximum iterations set to less than one. No DataPoints will be added to Analysis '" << analysis.name() << "', and the Algorithm will be marked complete."); markComplete(); return result; } OptionalInt mxSim = options.maxSims(); DataPointVector dataPoints = analysis.getDataPoints("DOE"); int totPoints = dataPoints.size(); if (mxSim && (totPoints >= *mxSim)) { LOG(Info,"Analysis '" << analysis.name() << "' already contains " << totPoints << " DataPoints added by the DesignOfExperiments algorithm, which meets or exceeds the " << "maximum number specified in this algorithm's options object, " << *mxSim << ". " << "No data points will be added and the Algorithm will be marked complete."); markComplete(); return result; } m_iter = 1; // determine all combinations std::vector< std::vector<QVariant> > variableValues; for (const Variable& variable : analysis.problem().variables()) { // variable must be DiscreteVariable, otherwise !isCompatibleProblemType(analysis.problem()) DiscreteVariable discreteVariable = variable.cast<DiscreteVariable>(); IntVector dvValues = discreteVariable.validValues(true); std::vector< std::vector<QVariant> > currentValues = variableValues; for (IntVector::const_iterator it = dvValues.begin(), itEnd = dvValues.end(); it != itEnd; ++it) { std::vector< std::vector<QVariant> > nextSet = currentValues; if (currentValues.empty()) { variableValues.push_back(std::vector<QVariant>(1u,QVariant(*it))); } else { for (std::vector<QVariant>& point : nextSet) { point.push_back(QVariant(*it)); } if (it == dvValues.begin()) { variableValues = nextSet; } else { variableValues.insert(variableValues.end(),nextSet.begin(),nextSet.end()); } } } } // create data points and add to analysis for (const std::vector<QVariant>& value : variableValues) { DataPoint dataPoint = analysis.problem().createDataPoint(value).get(); dataPoint.addTag("DOE"); bool added = analysis.addDataPoint(dataPoint); if (added) { ++result; ++totPoints; if (mxSim && (totPoints == mxSim.get())) { break; } } } if (result == 0) { LOG(Trace,"No new points were added, so marking this DesignOfExperiments complete."); markComplete(); } return result; }
int RateMeyerDiscrete::computePatternRates(DoubleVector &pattern_rates, IntVector &pattern_cat) { pattern_rates.insert(pattern_rates.begin(), begin(), end()); pattern_cat.insert(pattern_cat.begin(), ptn_cat, ptn_cat + size()); return ncategory; }
bool Split::containAny(IntVector &tax_id) { for (IntVector::iterator it = tax_id.begin(); it != tax_id.end(); it++) if (containTaxon(*it)) return true; return false; }