Point DefenseStrategy::eval(const Table& table, Point pos) {
    Soldier type = table[pos]->soldier;
    const Point origin{0, 0};
    std::vector<Point> enemies;
    for (Point p : arrayRange(table)) {
        if (table[p] && table[p]->enemy && (table[p]->soldier == type ||
                less(table[p]->soldier, type))) {
            enemies.push_back(p);
        }
    }
    Point nearest;
    if (enemies.empty()) {
        nearest = Point{19, 19};
    } else {
        nearest = *findBest(enemies, 
                [&](Point p) {
                    if (p.x < pos.x && p.y < pos.y) {
                            return distance(p, origin);
                        } else {
                            return distance(p, pos) + 1000;
                        }
                });
    }
    Point stepTo = move(table, pos, nearest);
    //std::cerr << "Defense: " << pos << " --> " << nearest << " [" <<
            //stepTo << "]\n";
    return attackRunOverride(table, pos, stepTo, true);
}
Beispiel #2
0
QString InputMatcher::findBest(int set, int maxset, bool isDigit, const QString &str) const
{
    // only return if error values given.
    if (!qualifiedSets)
	return QString();
    if (set == maxset)
	return str;
    else if (set >maxset)
	return QString();

    // add word as spelt.
    const InputMatcherGuessList *gl = nsets[set];
    InputMatcherGuessList::const_iterator it = gl->begin();
    QList<int> avoidLength;
    avoidLength.append(0);
    while(it != gl->end()) {
	IMIGuess guess = *it;
	QChar ch(guess.c);
	if (gl->shift)
	    ch = convertToUpper(ch);
	if (!avoidLength.contains(guess.length) && ch.isDigit() == isDigit) {
	    QString r = findBest(set+guess.length, maxset, isDigit, str+ch);
	    if (!r.isEmpty())
		return r;
	    avoidLength.append(guess.length);
	}
	++it;
    }
    return QString();
}
FindResult PyramidTemplateMatcher::next(){
   TimingBlock tb("PyramidTemplateMatcher::next()");
   if (data.isSourceSmallerThanTarget()){
      //std:cerr << "PyramidTemplateMatcher: source is smaller than the target" << endl;
      return FindResult(0,0,0,0,-1);
   }
   if (lowerPyramid != NULL)
      return nextFromLowerPyramid();

   double detectionScore;
   Point detectionLoc;
   if(!_hasMatchedResult){
      detectionScore = findBest(data, NULL, result, detectionLoc);
      _hasMatchedResult = true;
   }
   else{
#ifdef ENABLE_GPU
      if(_use_gpu)
         gpu::minMaxLoc(gResult, NULL, &detectionScore, NULL, &detectionLoc);
      else
#endif
      {
         minMaxLoc(result, NULL, &detectionScore, NULL, &detectionLoc);
      }

   }

   const Mat& target = data.getTarget();

   int xmargin = target.cols/3;
   int ymargin = target.rows/3;
   eraseResult(detectionLoc.x, detectionLoc.y, xmargin, ymargin);
   
   return FindResult(detectionLoc.x,detectionLoc.y,target.cols,target.rows,detectionScore);
}
Beispiel #4
0
int FaceList::insert(Face *f, int weight)
{
	if (contains(f)) {
		Face *mf = match(f);
		mf->adjustCenter(f->center());
		int w = m_faces[mf] + weight;
		m_faces[mf] = w;
		m_misses[mf] = 0;
		findBest();
		return(m_faces[mf]);
	}
	m_faces[f] = weight;
	m_misses[f] = 0;
	findBest();
	return(weight);
}
Beispiel #5
0
void ACS::global_updatePheromeno() 
{
	ReturnFlag rf;
	int i, j, dim;
	dim = m_pop[0]->getNumDim();
	m_impRadio = 0;
	for (i = 0; i<m_popsize; i++)
	{
		double temp = m_pop[i]->data().m_obj[0];
		rf = m_pop[i]->evaluate();
		if (temp > m_pop[i]->data().m_obj[0])
			m_impRadio++;
		if (rf == Return_Terminate) break;
	}
	vector<int> bestIdx = findBest();
	if (!m_isHaveGlobalBest || m_globalBest < m_pop[bestIdx[0]]->representative()) //update globally best tour 
	{
		m_globalBest = m_pop[bestIdx[0]]->representative(); //deep copy
		m_isHaveGlobalBest = true;
	}
#ifdef OFEC_CONSOLE
	OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<Ant>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre);
#endif
	if (rf == Return_Terminate) return;
	double len = 1./m_globalBest.data().m_obj[0];
	vector<vector<int>> global_edges(dim);
	for (int i = 0; i < dim; i++)
	{
		global_edges[i].resize(dim);
	}
	for (int i = 0; i < dim; i++)
		for (int j = 0; j < dim; j++)
			global_edges[i][j] = 0;
	vector<int> edges(dim);
	for (int i = 0; i < dim; i++)
	{
		edges[i] = m_globalBest.data().m_x[i];
	}
	for (int i = 0; i < dim; i++)
	{
		global_edges[edges[i]][edges[(i+1)%dim]] = 1;
	}
	for (int i = 0; i < dim; i++)
		for (int j = i + 1; j < dim; j++) //symmetric
		{
			if (global_edges[i][j] || global_edges[j][i])
			{
				mvv_phero[i][j] = (1 - m_coeff)*mvv_phero[i][j] + m_coeff*len;
				mvv_phero[j][i] = mvv_phero[i][j];
			}
			else
			{
				mvv_phero[i][j] = (1 - m_coeff)*mvv_phero[i][j];
				mvv_phero[j][i] = mvv_phero[i][j];
			}
		}
}
Beispiel #6
0
ReturnFlag ACS::run_()
{
	int i, j, dim;
	initializeSystem();
	dim = m_pop[0]->getNumDim();
	m_iter = 0;

	if (m_stopCriterion == MIN_COVER){
		dynamic_cast<TermMean*>(m_term.get())->initialize(DBL_MAX);
	}

	while (!ifTerminating())
	{
#ifdef OFEC_DEMON
		for (i = 0; i<this->getPopSize(); i++)
			updateBestArchive(this->m_pop[i]->self());
		vector<Algorithm*> vp;
		vp.push_back(this);
		msp_buffer->updateBuffer_(&vp);
#endif
		for (i = 0; i < m_popsize; i++)
		{
			for (j = 1; j < dim; j++)
			{
				double q = Global::msp_global->mp_uniformAlg->Next();
				if (q <= m_Q)
					m_pop[i]->selectNextCity_Greedy(mvv_phero, m_beta);
				else
					m_pop[i]->selectNextCity_Pro(mvv_phero, m_beta);
				local_updatePheromeno(i);
			}
			local_updatePheromeno(i, true);
		}
		global_updatePheromeno();
		resetAntsInfo();
		++m_iter;
		if (m_stopCriterion == MIN_COVER) {
			dynamic_cast<TermMean*>(m_term.get())->countSucIter(mean());
		}
		//cout<<" "<<Global::msp_global->mp_problem->getBestSolutionSoFar().getObjDistance(CAST_TSP->getGOpt()[0].data().m_obj)<<" "<<m_stopCount<<endl;
#ifdef OFEC_CONSOLE
		double tempdif = 0;
		for (int i = 0; i < m_popsize; i++)
			tempdif += m_pop[i]->self().getDistance(Solution<CodeVInt>::getBestSolutionSoFar());
		tempdif /= m_popsize;
		double impr = static_cast<double>(m_impRadio) / m_popsize;
		OptimalEdgeInfo::getOptimalEdgeInfo()->recordiffAndImp(Global::msp_global->m_runId, Global::msp_global->mp_problem->getEvaluations(), fabs(tempdif), impr);
#endif
	}
#ifdef OFEC_CONSOLE
	vector<int> bestIdx = findBest();
	OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<Ant>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre, false);

	OptimalEdgeInfo::getOptimalEdgeInfo()->recordLastInfo(Global::msp_global->m_runId, Global::msp_global->mp_problem->getEvaluations());
#endif
	return Return_Terminate;
}
Beispiel #7
0
int FaceList::remove(Face *f)
{
	if (containsExactly(f)) {
		int w = m_faces[f];
		m_faces.erase(f);
		findBest();
		return(w);
	}
	return(0);
}
Beispiel #8
0
int FaceList::miss(Face *f)
{
	if (containsExactly(f)) {
		m_misses[f] = m_misses[f] + 1;
		int r = m_misses[f];
		findBest();
		return(r);
	} else {
		return(0);
	}
}
Beispiel #9
0
int main(int argc, char * argv[]){
    Population * pop, * selected;
    Individual * best_solution;
    int generation_num;
    
    initParameters(argc, argv);
    pop = genSeededPopulation(POP_SIZE);
    
#if (defined DIVERSITY)
    printGeneComposition(pop);
#endif

    determineFitness(pop);
    sortByFitness(pop);

    generation_num = 0;
    while(generation_num < MAX_NUM_GENERATIONS){
        
    #if  (defined VERBOSE || defined DIVERSITY)
        fprintf(stdout, "\n-----------------   GENERATION %d   -----------------\n", generation_num + 1);
        printPopulation(pop);
    #endif
        
        // FIX - use function pointers instead of flags + if statement
        if(selection_type == 1)
            selected = tournamentSelection(pop);
        else 
            selected = randomSelection(pop);
            
        // FIX - use function pointers instead of flags + if statement
        evolvePopulation(selected, crossover_type, mutation_type);
        determineFitness(selected);
        
        // FIX - use function pointers instead of flags + if statement
        if(replacement_type == 1)
            pop = replaceAll(pop, selected);
        else  
            pop = retainBest(pop, selected);

        generation_num++;
    }
    
    fprintf(stdout, "\nFINAL RESULT:\n");
    printPopulation(pop);
    
    fprintf(stdout, "\nBEST SOLUTION:\n");
    best_solution = findBest(pop);
    printIndividual(best_solution);
    
    freePopulation(pop);
    freeParameters();
    return EXIT_SUCCESS;
} 
Beispiel #10
0
QString InputMatcher::findBest(const QString &prefix, const QString &suffix, bool isDigit) const
{
    int pl = prefixLength(prefix);
    int sl = suffixLength(suffix);
    if (pl == -1 || sl == -1 || (pl + sl >= (int)nsets.size()))
	return QString();
    QString nword = findBest(pl, nsets.size()-sl, isDigit);
    if (nword.isEmpty())
	return QString();
    else
	return prefix+nword+suffix;
}
Beispiel #11
0
void handle() {
  int i;
  reset();
  for (i = 0; i < n; i++) {
    int a, b, c;
    scanf ("%d %d %d ", &a, &b, &c);
    int cost = (a + b) * c;
    canGo[a][b] = min(canGo[a][b], cost);
    canGo[b][a] = min(canGo[b][a], cost);
  }
  int s;
  scanf ("%d %d ", &s, &tar);
  int rrr = findBest(s);
  printf("%d.%02d\n", rrr / 100, rrr % 100);
}
Beispiel #12
0
void
ITM<ITM_TRAITS>::operator()( const observation_type & o )
{
    node_type best;
    node_type second;

    boost::tie( best, second ) = findBest( o );

    if ( best == none_ ) {
        node_type n = boost::add_vertex( graph_ );
        graph_[n].centroid = o;
        std::cerr << "Add vertex: " << graph_[n].centroid << std::endl;
        return;
    }

    if ( second == none_ ) {
        if ( distance_( graph_[best].centroid, o ) > insertionDistance_ ) {
            second = best;
            best = boost::add_vertex( graph_ );
            graph_[best].centroid = o;
            std::cerr << "Add vertex: " << graph_[best].centroid << std::endl;
        } else {
            return;
        }
    }

    assert( best != second );
    // This assumes that graph do not handle parallel edges
    observation_type & bestCentroid = graph_[best].centroid;
    observation_type & secondCentroid = graph_[second].centroid;

    if ( distance_( bestCentroid, secondCentroid ) < 2 * insertionDistance_ ) {
        boost::add_edge( best, second, graph_ );
        boost::add_edge( second, best, graph_ );
    }

    bestCentroid += epsilon_ * ( o - bestCentroid );

    handleDeletions( best, second );
    handleInsertions( o, best, second );
}
FindResult PyramidTemplateMatcher::nextFromLowerPyramid(){
   FindResult match = lowerPyramid->next();

   int x = match.x*factor;
   int y = match.y*factor;

   
   // compute the parameter to define the neighborhood rectangle
   int x0 = max(x-(int)factor,0);
   int y0 = max(y-(int)factor,0);
   int x1 = min(x+data.target.cols+(int)factor,data.source.cols);
   int y1 = min(y+data.target.rows+(int)factor,data.source.rows);
   Rect roi(x0,y0,x1-x0,y1-y0);

   Point detectionLoc;
   double detectionScore = findBest(data, &roi, result, detectionLoc);

   detectionLoc.x += roi.x;
   detectionLoc.y += roi.y;

   return FindResult(detectionLoc.x,detectionLoc.y,data.target.cols,data.target.rows,detectionScore);
}
Beispiel #14
0
Datei: mancala.c Projekt: wfei/hw
char findBestComputerMove(Hole originalBoard[]) {
    printFlag = 0;
    int i, j, k;
    // make a copy of the originalBoard
    Hole newBoard[BOARDSIZE];
    copyBoard(newBoard, originalBoard);

    
    // construct the searching tree
    Node root;
    initSearchTree(newBoard, &root);
    
    // construct first level. Root is at level 0
    int depth = 3;
    expandTree(&root, depth, 1);
    Node* bestNode;
    bestNode = findBest(&root, depth);
    char computerMove = findBestMove(bestNode, &root);
    deleteTree(&root, &root);
    printFlag = 1;
    return computerMove;
}
Beispiel #15
0
ReturnFlag NFishSwarm::evolve(){
	ReturnFlag rf=Return_Normal;
	//new prey behavior
	for(auto &fish:m_pop){
		for(int i=0;i<m_tryNumber;++i){
			rf=fish->prey(m_visual);
			if(rf!=Return_Normal) return rf;
			updateBestArchive(fish->self());
		}
	}
	
	//new follow behavior
	for(auto &fish:m_pop){
		rf=fish->follow(*m_best[0],m_visual);
		if(rf!=Return_Normal) return rf;
		updateBestArchive(fish->self());
	}

	//new swarm behevior
	computeCenter();
	findBest();
	for(auto &fish:m_pop){
		if(m_center>fish->self()){
			if(fish->m_index!=m_bestIdx[0]){
				rf=fish->swarm(m_center,m_visual);
				if(rf!=Return_Normal) return rf;
			}else{
				fish->self()=m_center;	
			}
			updateBestArchive(fish->self());
		}
	}
	updateVisual();
	updateCurRadius();
	m_iter++;
	return rf;
}
Beispiel #16
0
QList<unsigned char> cPathfinding::find(P_CHAR pChar, const Coord &from, const Coord &to)
{
	QList<unsigned char> result;
	int i;

	// We can only calculate a path on the normal maps and if the destination is not out of range
	if (from.isInternalMap() || from.distance(to) > (unsigned int)areaSize) {
		return result;
	}

	memset(touched, 0, sizeof(bool) * nodeCount); // Clear the touched nodes
	this->goal = to; // Save the goal

	// Actually th�s should be the x/y offset of our area
	xoffset = (from.x + to.x - areaSize) / 2;
	yoffset = (from.y + to.y - areaSize) / 2;

	int fromNode = getNodeIndex(from.x, from.y, from.z);
	int toNode = getNodeIndex(to.x, to.y, to.z);
	openlist = fromNode; // Where are we

	// Initialize the node
	nodes[fromNode].cost = 0;
	nodes[fromNode].total = heuristic(from.x - xoffset, from.y - yoffset, from.z);
	nodes[fromNode].parent = -1;
	nodes[fromNode].next = -1;
	nodes[fromNode].prev = -1;
	nodes[fromNode].z = from.z;

	// We touched this node
	onopen[fromNode] = true;
	touched[fromNode] = true;

	int depth = 0;
	int newTotal, newCost;

	// This is controlled by the npc moving. Some npcs can fly (move over impassables)
	// others can open doors
	ignoreDoors = false;
	ignoreMovableImpassables = false;
	int successors[8]; // List of successor nodes used in subsequent iterations. Never more than 8
	int successorCount; // Number of successors found

	while (openlist != -1) {
		if (++depth > maxDepth)
			break; // Break if we would exceed the maximum iteration count

		int bestnode = findBest(openlist);

		// Get adjacent nodes that we can walk to
		successorCount = getSuccessors(bestnode, pChar, successors);

		if (successorCount == 0) {
			break; // We've run into a situation where we'll never find a suitable successor
		}

		// Follow every possible successor
		for (i = 0; i < successorCount; ++i) {
			int successor = successors[i];

			if (touched[successor]) {
				continue; // If we worked on the node already, skip this part
			}

			// calculate the cost of the successor based on the currents node cost
			newCost = nodes[bestnode].cost + 1;
			newTotal = newCost + heuristic(successor % areaSize, (successor / areaSize) % areaSize, nodes[successor].z);

			// Always execute, !wasTouched was always true here
			// if ( !wasTouched || m_Nodes[newNode].total > newTotal )
			nodes[successor].parent = bestnode;
			nodes[successor].cost = newCost;
			nodes[successor].total = newTotal;
			addToChain(successor);

			// We found our target
			if (successor == toNode) {
				int pathCount = 0; // Stack allocation speed isn't a concern here anymore
				int parent = nodes[successor].parent;

				// Record the path in reverse order
				while (parent != -1) {
					path[pathCount++] = getDirection(parent % areaSize, (parent / areaSize) % areaSize, successor % areaSize, (successor / areaSize) % areaSize);
					successor = parent; // Track back
					parent = nodes[successor].parent;

					if (successor == fromNode) {
						break;
					}
				}

				int backtrack = 0;
				while (pathCount != 0) {
					result.append( path[--pathCount] );
				}
				return result; // Immediately return
			}
		}
	}

	return result; // Nothing found
}
Beispiel #17
0
QgsEditorWidgetWrapper* QgsEditorWidgetRegistry::create( QgsVectorLayer* vl, int fieldIdx, QWidget* editor, QWidget* parent, const QgsAttributeEditorContext &context )
{
  const QString fieldName = vl->fields().field( fieldIdx ).name();
  const QgsEditorWidgetSetup setup = findBest( vl, fieldName );
  return create( setup.type(), vl, fieldIdx, setup.config(), editor, parent, context );
}
//essentially an update
void Evolve::evolve(Population &pop)
{
    typedef std::pair<MEMBER*, SCORE>  data_pair;
    
    auto sort = findBest(pop);
    
    std::vector<data_pair>fin_sort(sort.begin(), sort.end() );
    std::sort(fin_sort.begin(), fin_sort.end(), [](const data_pair& that, const data_pair& thus)
              {
                  return that.second < thus.second;
              }
              );
    
    //find two best and copy them temporarily
    auto end_it = fin_sort.rbegin();
    MEMBER first = std::move(*end_it->first);
    end_it++;
    MEMBER second = std::move(*end_it->first);
    
    //checks best
    if(sort.rbegin()->second > best.first)
    {
        best = {sort.rbegin()->second, *first};
    }
    
    int START = 1;
    
    //adds to mode
    decltype(mode)::value_type data = {START, {first->getLemons(), first->getSugar(), first->getPrice()} };
    int val = DATA_FIND(mode, data);
    if(val != 0)
    {
        //adds one to mode if value is already placed
        decltype(data) newdata = {val, data.second};
        int pos = std::find(mode.begin(), mode.end(), decltype(newdata){newdata}) - mode.begin();
        mode.at(pos).first++;
    }
    else
    {
        mode.push_back(data);
    }
    
    //debug
    std::cout << first->getLemons() << std::endl;
    std::cout << first->getSugar() << std::endl;
    std::cout << first->getPrice() << std::endl;
    std::cout << "Profit assuming 100 chances: " << sort.rbegin()->second << std::endl;
    
    
    
    //clear the old vector
    clear(pop);
    
    //generate rest to fill up population size
    for(int i = 0; i < POP_SIZE - 2; i++)
    {
        pop.addIndividual(generate(*first, *second) );
    }
    
    //add in parents
    pop.addIndividual(std::move(first) );
    pop.addIndividual(std::move(second) );
}
Beispiel #19
0
void MMAS::updatePheromeno()
{
	ReturnFlag rf;
	int i, j, dim;
	dim = m_pop[0]->getNumDim();
	m_impRadio = 0;
	for (i = 0; i<m_popsize; i++)
	{
		double temp = m_pop[i]->data().m_obj[0];
		rf = m_pop[i]->evaluate();
		if (temp > m_pop[i]->data().m_obj[0])
			m_impRadio++;
		if (rf == Return_Terminate) break;
	}
	vector<int> bestIdx = findBest();
	if (!m_isHaveGlobalBest || m_globalBest < m_pop[bestIdx[0]]->representative()) //update globally best tour 
	{
		m_globalBest = m_pop[bestIdx[0]]->representative(); //deep copy
		m_restartBest = m_pop[bestIdx[0]]->representative(); //deep copy
		m_isHaveGlobalBest = true;
		m_isHaveRestartBest = true;

		m_restartFoundBest = m_iter;
		m_branchFactor = nodeBranching();
		updatePheroMinAndMax();
	}
	if (!m_isHaveRestartBest || m_restartBest < m_pop[bestIdx[0]]->representative())
	{
		m_restartBest = m_pop[bestIdx[0]]->representative(); //deep copy
		m_restartFoundBest = m_iter;
		m_isHaveRestartBest = true;
	}
#ifdef OFEC_CONSOLE
	OptimalEdgeInfo::getOptimalEdgeInfo()->recordEdgeInfo<Ant>(Global::msp_global.get(), Solution<CodeVInt>::getBestSolutionSoFar(), m_pop, m_num, m_popsize, m_saveFre);
#endif
	if (rf == Return_Terminate) return;
	for (i = 0; i < dim; i++)
		for (j = i+1; j < dim; j++)
		{
			mvv_phero[i][j] = (1 - m_rho) * mvv_phero[i][j];
			mvv_phero[j][i] = mvv_phero[i][j];
		}
	if (m_iter % m_uGB)
	{
		double len = 1.0 / m_pop[bestIdx[0]]->data().m_obj[0];
		for (i = 0; i < dim; i++)
		{
			int cur = m_pop[bestIdx[0]]->data().m_x[i];
			int next = m_pop[bestIdx[0]]->data().m_x[(i + 1) % dim];
			mvv_phero[cur][next] += len;
			mvv_phero[next][cur] = mvv_phero[cur][next];
		}
	}
	else
	{
		double len = 1.0 / m_restartBest.data().m_obj[0];
		for (i = 0; i < dim; i++)
		{
			int cur = m_restartBest.data().m_x[i];
			int next = m_restartBest.data().m_x[(i + 1) % dim];
			mvv_phero[cur][next] += len;
			mvv_phero[next][cur] = mvv_phero[cur][next];
		}
	}
	m_uGB = 25;
	checkPheromoneTrailLimits();
}
Beispiel #20
0
QString InputMatcher::numberWord(const QString &prefix, const QString &suffix) const
{
    return findBest(prefix, suffix, TRUE);
}
Beispiel #21
0
bool MaxRects::pack() {
	m_bins.clear();

	m_bins.push_back({
		false, std::list<Rect>(1, { 0, 0, m_config.m_width, m_config.m_height })
	});

	while (!m_rectangles.empty()) {
		BinIt bin;
		RectIt freeRect;
		RectDataIt rect;
		bool flip;

		// If it couldn't find a free spot, add bin
		if (!findBest(bin, freeRect, rect, flip)) {
			// Can't add a new bin
			if (m_config.m_maxBins > 0 && m_bins.size() >= (unsigned int) m_config.m_maxBins) {
				for (auto& rect : m_rectangles)
					rect->m_bin = std::numeric_limits<unsigned int>::max();

				return false;
			}

			for (auto& bin: m_bins)
				bin.m_full = true;

			m_bins.push_back({
				false, std::list<Rect>(1, { 0, 0, m_config.m_width, m_config.m_height })
			});
			continue;
		}

		// Update rect data
		auto& rectRef = **rect;

		rectRef.m_x = freeRect->m_x;
		rectRef.m_y = freeRect->m_y;
		rectRef.m_flipped = flip;
		rectRef.m_bin = std::distance(m_bins.begin(), bin);

		// Split intersecting rectangles
		std::list<Rect> newRects;

		const auto width  = flip ? rectRef.m_h : rectRef.m_w;
		const auto height = flip ? rectRef.m_w : rectRef.m_h;

		bin->m_freeRects.remove_if([&newRects, &rectRef, &width, &height](Rect& freeRect) {
			if (rectRef.m_x >= freeRect.m_x + freeRect.m_w || rectRef.m_x + width <= freeRect.m_x ||
				rectRef.m_y >= freeRect.m_y + freeRect.m_h || rectRef.m_y + height <= freeRect.m_y)
				return false;

			if (rectRef.m_x < freeRect.m_x + freeRect.m_w && rectRef.m_x + width > freeRect.m_x) {
				if (rectRef.m_y > freeRect.m_y && rectRef.m_y < freeRect.m_y + freeRect.m_h)
					newRects.push_back({ freeRect.m_x, freeRect.m_y, freeRect.m_w, rectRef.m_y - freeRect.m_y });

				if (rectRef.m_y + height < freeRect.m_y + freeRect.m_h)
					newRects.push_back({ freeRect.m_x, rectRef.m_y + height, freeRect.m_w, freeRect.m_y + freeRect.m_h - (rectRef.m_y + height) });
			}

			if (rectRef.m_y < freeRect.m_y + freeRect.m_h && rectRef.m_y + height > freeRect.m_y) {
				if (rectRef.m_x > freeRect.m_x && rectRef.m_x < freeRect.m_x + freeRect.m_w)
					newRects.push_back({ freeRect.m_x, freeRect.m_y, rectRef.m_x - freeRect.m_x, freeRect.m_h });

				if (rectRef.m_x + width < freeRect.m_x + freeRect.m_w)
					newRects.push_back({ rectRef.m_x + width, freeRect.m_y, freeRect.m_x + freeRect.m_w - (rectRef.m_x + width), freeRect.m_h });
			}

			return true;
		});

		newRects.remove_if([&bin](Rect& rect) {
			for (auto& other : bin->m_freeRects)
				if (rect.m_x >= other.m_x && rect.m_y >= other.m_y &&
					rect.m_x + rect.m_w <= other.m_x + other.m_w &&
					rect.m_y + rect.m_h <= other.m_y + other.m_h)
					return true;

			return false;
		});

		bin->m_freeRects.remove_if([&newRects](Rect& rect) {
			for (auto& other : newRects)
				if (rect.m_x >= other.m_x && rect.m_y >= other.m_y &&
					rect.m_x + rect.m_w <= other.m_x + other.m_w &&
					rect.m_y + rect.m_h <= other.m_y + other.m_h)
					return true;

			return false;
		});

		bin->m_freeRects.splice(bin->m_freeRects.end(), newRects);
		
		// Remove rect
		m_rectangles.erase(rect);
	}

	return true;
}
Beispiel #22
0
QString InputMatcher::writtenWord(const QString &prefix, const QString &suffix) const
{
    return findBest(prefix, suffix, FALSE);
}
Beispiel #23
0
void multiDS(int n, double *x, double cc, double ce, double lmin,
             double lstart, int maxiter)
{
   int i, imin, replaced, iter = 0;
   double **xs, **xr, **xe, **xc, *fs, *fr, *fe, *fc, fsmin, frmin,
      femin, fcmin, ssize;
   FILE *fp;
   void initSimplex(int, double *, double **, double);
   void printSimplex(int, int, double **, double *);
   void findBest(int, double **, double *, int *, double *);
   void copySimplex(int, double **, double **, double *, double *);
   double simplexSize(int, double **);
   void vecAdd(int, double *, double *, double *, double);
   double dmin(int, double *);
   void mpi_assign(int);
   void mpi_distribute(int, double *);

   /* Initial size of simplex */
   ssize = lstart;

   /* Check validity of input parameters */
   if(cc <= 0.0 || cc >= 1.0) {
      printf("multiDS: contraction coefficient must be in (0,1)\n");
      exit(0);
   }

   if(ce <= 1.0) {
      printf("multiDS: expandion coefficient must be > 1\n");
      exit(0);
   }

   if(ssize < lmin) {
      printf("multiDS: starting simplex size is < minimum\n");
      printf("         give lstart > lmin\n");
      exit(0);
   }

   printf("Parameters for search:\n");
   printf("   Contraction factor     = %e\n", cc);
   printf("   Expansion   factor     = %e\n", ce);
   printf("   Starting simplex size  = %e\n", ssize);
   printf("   Minimum  simplex size  = %e\n", lmin);
   printf("   Maximum number of iter = %d\n", maxiter);

   /* Allocate memory */
   xs = (double **) calloc((n + 1), sizeof(double *));
   xr = (double **) calloc((n + 1), sizeof(double *));
   xe = (double **) calloc((n + 1), sizeof(double *));
   xc = (double **) calloc((n + 1), sizeof(double *));
   fs = (double *) calloc(n + 1, sizeof(double));
   fr = (double *) calloc(n + 1, sizeof(double));
   fe = (double *) calloc(n + 1, sizeof(double));
   fc = (double *) calloc(n + 1, sizeof(double));
   for(i = 0; i < n + 1; i++) {
      xs[i] = (double *) calloc(n, sizeof(double));
      xr[i] = (double *) calloc(n, sizeof(double));
      xe[i] = (double *) calloc(n, sizeof(double));
      xc[i] = (double *) calloc(n, sizeof(double));
   }


   /* Initialize the simplex */
   initSimplex(n, x, xs, ssize);

   /* Assign evaluations to different proc */
   mpi_assign(n);

   /* Calculate initial function values */
   /* Zeroth vertex is starting vertex, cost = 1. No need to calculate again
    * since it is already done in multiDS_driver.c */
   fs[0] = cost0;

   for(i = 1; i < n + 1; i++) {
      if(proc[i] == myproc)
         fs[i] = objFun(n, xs[i]);
   }

   /* Distribute cost functions */
   mpi_distribute(n, fs);

   printf("Initial simplex and function values:\n");
   printSimplex(0, n, xs, fs);

   /* Find best vertex and put in first position */
   findBest(n, xs, fs, &imin, &fsmin);

   if(myproc == 0)
      fp = fopen("cost.dat", "w");

   /* Main iteration loop */
   while(ssize > lmin && iter < maxiter) {
      printf("Iteration = %d\n\n", iter + 1);

      replaced = 0;
      while(!replaced && ssize > lmin) { /* inner repeat loop */

         /* rotation step */
         printf("   Rotation:\n");
         for(i = 1; i <= n; i++) {
            vecAdd(n, xs[0], xs[i], xr[i], 1.0);
            if(proc[i] == myproc)
               fr[i] = objFun(n, xr[i]);
         }
         mpi_distribute(n, fr);
         printSimplex(1, n, xr, fr);

         frmin = dmin(n, fr);
         replaced = (frmin < fs[0]) ? 1 : 0;
         if(replaced) {
            /* expansion step */
            printf("   Expansion:\n");
            for(i = 1; i <= n; i++) {
               vecAdd(n, xs[0], xs[i], xe[i], ce);
               if(proc[i] == myproc)
                  fe[i] = objFun(n, xe[i]);
            }
            mpi_distribute(n, fe);
            printSimplex(1, n, xe, fe);

            femin = dmin(n, fe);
            if(femin < frmin)
               copySimplex(n, xe, xs, fe, fs); //accept expansion
            else
               copySimplex(n, xr, xs, fr, fs); //accept rotation
         }
         else {
            /* contraction step */
            printf("   Contraction step:\n");
            for(i = 1; i <= n; i++) {
               vecAdd(n, xs[0], xs[i], xc[i], -cc);
               if(proc[i] == myproc)
                  fc[i] = objFun(n, xc[i]);
            }
            mpi_distribute(n, fc);
            printSimplex(1, n, xc, fc);

            fcmin = dmin(n, fc);
            replaced = (fcmin < fs[0]) ? 1 : 0;
            copySimplex(n, xc, xs, fc, fs); //accept contraction
         }

         /* Length of smallest edge in simplex */
         ssize = simplexSize(n, xs);

      }                         /* End of inner repeat loop */

      ++iter;

      /* Find best vertex and put in first position */
      findBest(n, xs, fs, &imin, &fsmin);

      printf("\n");
      printf("Minimum length of simplex = %12.4e\n", ssize);
      printf("Minimum function value    = %12.4e\n", fs[0]);
      printf("-------------------------------------------------\n");
      if(myproc == 0) {
         fprintf(fp, "%5d %20.10e %20.10e %5d\n", iter, fs[0], ssize, imin);
         fflush(fp);
      }
   }                            /* End of main iteration loop */
   if(myproc == 0)
      fclose(fp);

   /* Copy best vertex for output */
   for(i = 0; i < n; i++)
      x[i] = xs[0][i];

   /* Best vertex found */
   printf("Best vertex:\n");
   for(i = 0; i < n; i++)
      printf("%e ", x[i]);
   printf("\n");


   /* Free memory */
   for(i = 0; i < n + 1; i++) {
      free(xs[i]);
      free(xr[i]);
      free(xe[i]);
      free(xc[i]);
   }
   free(xs);
   free(xr);
   free(xe);
   free(xc);
   free(fs);
   free(fr);
   free(fe);
   free(fc);
}