/*Dado uma posicao, checa se para alguma direcao existe um robo, e retorna qual direcao esta o mais perto, contando giradas necessarias*/ int searchNearestRobot (Grid *g, Position p, Robot *r) { int i, min = 500, best_dir = 0, cont; Position s; for (i = 0; i < 6; i++) { /*Conta para chegar o numero de viradas necessarias ja que elas gastam um turno*/ cont = 1 + quickTurn (r->dir, i); s = getNeighbor (p, i); while (limiteDoMapa (s, g->m, g->n)) { if (isRobot (g, s)) { if(cont < min) { min = cont; best_dir = i; break; } } s = getNeighbor (s, i); } } /*Nao existe robos nas direções ao redor do jogador*/ if (min == 500) return -1; else return best_dir; }
int deveDesviar (Position pos, Grid *grid, Robot *r) { int i; Projectile *proj; Position proj_pos, andar_pos; for (i = 0; i < 6; i++) { if (adjacentes[i] == 3) { proj_pos = getNeighbor (pos, i); proj = &grid->map[proj_pos.x][proj_pos.y].object.projectile; andar_pos = getNeighbor (pos, r->dir); if ((proj->dir + 3)%6 == i) { if (valid (andar_pos, grid->m, grid->n, grid)) if (r->dir != i && r->dir != (i + 3)%6) return 1; /*pode desviar reto*/ else return -2; /*ou atira para destruir o tiro, ou põe bloco*/ else return -1; /*gira para o lado mais proximo para tentar fugir*/ } } } return 0; }
CGrid::SIMULATION_ERROR CGrid::simulate(char* outfile, int steps, float delta_t, double pumaBirthRate, double pumaDeathRate, double pumaFusionRate, double hareBirthRate, double hareDeathRate, double hareFusionRate){ assert(0 != outfile && "Invalid pointer for density input"); for(float T=0; T<steps; T=T+delta_t){ for(int i = 0; i < _dim_y; ++i){ for(int j = 0; j < _dim_x; ++j){ if(_cells[(i+1)*_dim_x_with_halo + (j+1)].isLand()){ const CCell* northCell = getNeighbor(i+1,j+1,NORTH); assert(northCell != 0); const CCell* southCell = getNeighbor(i+1,j+1,SOUTH); assert(southCell != 0); const CCell* eastCell = getNeighbor(i+1,j+1,EAST); assert(eastCell != 0); const CCell* westCell = getNeighbor(i+1,j+1,WEST); assert(westCell != 0); CCell* currentCell = _cells+(i+1)*_dim_x_with_halo+(j+1); unsigned int surroundingLandCells = northCell->isLand()+southCell->isLand()+eastCell->isLand()+westCell->isLand(); currentCell->calcNewPumaDensity(northCell->getPumaDensity(),southCell->getPumaDensity(), eastCell->getPumaDensity(), westCell->getPumaDensity(), currentCell->getHareDensity(), delta_t, pumaBirthRate, pumaDeathRate, pumaFusionRate, surroundingLandCells); currentCell->calcNewHareDensity(northCell->getHareDensity(),southCell->getHareDensity(), eastCell->getHareDensity(), westCell->getHareDensity(), currentCell->getPumaDensity(), delta_t, hareBirthRate, hareDeathRate, hareFusionRate, surroundingLandCells); } } } updateCells(); printHareDensity(); printPumaDensity(); } return SUCCESS; }
/*Dado uma posicao, checa se para alguma direcao existe um control point, e retorna qual direcao esta o mais perto, contando giradas necessárias*/ int searchNearestControl (Grid *g, Position p, Robot *r) { int i, min = 500, best_dir = 0, cont; for(i = 0; i < 6; i++) { /*Conta para chegar o numero de viradas necessarias ja que elas gastam um turno*/ cont = 1 + quickTurn (r->dir, i); Position s = getNeighbor (p,i); while(valid (s, g->m, g->n, g)) { if(isControlPoint (g,s)) { if(cont < min) { min = cont; best_dir = i; break; } } cont++; s = getNeighbor (s, i); } } /*Nao existe control points no mapa*/ if (min == 500) return -1; else return best_dir; }
SupportRenumbering makeBandedSimulatedAnnealing(const std::vector<SNPSupport>& supports, SupportRenumbering start, int iterations, double temperature, double temperatureMultiplier) { SupportRenumbering best = start; double bestEnergy = getEnergy(renumberSupports(supports, best)); SupportRenumbering current = best; double currentEnergy = bestEnergy; std::mt19937 mt {(size_t)std::chrono::system_clock::now().time_since_epoch().count()}; std::uniform_real_distribution<double> changeCurrent {0, 1}; for (int i = 0; i < iterations; i++) { SupportRenumbering newRenumbering = getNeighbor(current, supports); assert(newRenumbering.checkValidity()); double newEnergy = getEnergy(renumberSupports(supports, newRenumbering)); if (newEnergy < bestEnergy) { best = newRenumbering; bestEnergy = newEnergy; std::cerr << "iteration " << i << " new best " << bestEnergy << "\n"; } if (changeCurrent(mt) < std::min(1.0, exp((currentEnergy-newEnergy)/temperature))) { current = newRenumbering; currentEnergy = newEnergy; } temperature *= temperatureMultiplier; } return best; }
std::vector<OctreePath> getNeighbors(const OctreePath& origin, int type) { std::vector<OctreePath> result; auto f = [&origin, &result](const std::array<Symbol, 3>& direction) { auto n = getNeighbor(origin, direction); if (! n.empty()) { result.push_back(std::move(n)); } }; size_t size = (((NEIGHBORHOOD_FACE & type) == 0) ? 0 : 6) + (((NEIGHBORHOOD_EDGE & type) == 0) ? 0 : 12) + (((NEIGHBORHOOD_VERTEX & type) == 0) ? 0 : 8); result.reserve(size); if ((NEIGHBORHOOD_FACE & type) != 0) { std::for_each(FaceNeighbors.begin(), FaceNeighbors.end(), f); } if ((NEIGHBORHOOD_EDGE & type) != 0) { std::for_each(EdgeNeighbors.begin(), EdgeNeighbors.end(), f); } if ((NEIGHBORHOOD_VERTEX & type) != 0) { std::for_each(VertexNeighbors.begin(), VertexNeighbors.end(), f); } return result; }
Action Desviar (Position pos, Grid *grid, Robot *r){ int deve, i, dir_proj, dir_ini; Position p, proj_pos; Projectile *proj; deve = deveDesviar (pos, grid, r); /*Se estivermos num ponto de controle e nao estivermos sendo atacados*/ if (isControlPoint (grid, pos)) { dir_proj = searchNearestProjectile (grid, pos, r); dir_ini = searchNearestRobot (grid, pos, r); /* Caso seja encontrado um projetil numa direcao valida e caso exista municao realizamos uma acao */ if (dir_ini != -1 && dir_proj != -1 && r->bullets > 0 ) { if (dir_proj == r->dir) return SHOOT_CENTER; if (dir_proj == (r->dir + 1)%6) return SHOOT_RIGHT; if (dir_proj == (r->dir + 2)%6) return OBSTACLE_RIGHT; if (dir_proj == (r->dir + 3)%6) return OBSTACLE_CENTER; if (dir_proj == (r->dir + 4)%6) return OBSTACLE_LEFT; if (dir_proj == (r->dir + 5)%6) return SHOOT_LEFT; } } else { if(deve==1) return WALK; else if(deve==-1) { p=getNeighbor (pos, (r->dir+1)%6); if(limiteDoMapa (p, grid->m, grid->n) && (grid->map[p.x][p.y].type == NONE)) return TURN_RIGHT; else return TURN_LEFT; /*vai virar pra esquerda caso a posição da esquerda seja vazia, ou nem a da direita ou da esquerda seja vazia, ai ele vai ter q da uma volta*/ } else {/*sobrou só o caso -2*/ for (i = 0; i < 6; i++){ if (adjacentes[i] == 3){ proj_pos = getNeighbor (pos, i); proj = &grid->map[proj_pos.x][proj_pos.y].object.projectile; if ((proj->dir + 3)%6 == i){ if (r->dir == i) return SHOOT_CENTER; if (r->dir == (i + 3)%6) return OBSTACLE_CENTER; } } } } } return STAND; }
CompactArray<MazeCell*> MazeCell::findCompleteNeighbors() { CompactArray<MazeCell*> result; for(int i = 0; i < getWallCount(); i++) { MazeCell *nc = getNeighbor(i); if(nc != NULL && nc->allWallsVisible()) { result.add(nc); } } return result; }
void element::splitNeighbors(int longEdge) { int opnode, othernode, modEdge, otherEdge; int nbrLongEdge, nbrOpnode, nbrOthernode, nbrModEdge, nbrOtherEdge; elemRef nbr = getNeighbor(longEdge); edgeRef modEdgeRef, nbrModEdgeRef; // initializations of shortcuts to affected parts of element opnode = (longEdge + 2) % 3; othernode = longEdge; modEdge = opnode; otherEdge = (longEdge + 1) % 3; if (nbr.cid == myRef.cid) { // neighbor is local -> longEdge is local // initializations of shortcuts to affected parts of neighbor element nbrLongEdge = C->theElements[nbr.idx].findLongestEdge(); nbrOpnode = (nbrLongEdge + 2) % 3; nbrOthernode = (nbrOpnode+1) % 3; nbrModEdge = nbrOpnode; nbrOtherEdge = (nbrLongEdge + 1) % 3; if (!(C->theElements[nbr.idx].nodes[nbrOthernode] == nodes[othernode])) { nbrOthernode = (nbrOpnode+2) % 3; nbrModEdge = nbrOthernode; nbrOtherEdge = (nbrLongEdge + 2) % 3; } modEdgeRef = edges[modEdge]; nbrModEdgeRef = C->theElements[nbr.idx].edges[nbrModEdge]; // lock the perimeter if (edges[modEdge].lock(C)) { if (edges[otherEdge].lock(C)) { if (C->theElements[nbr.idx].edges[nbrModEdge].lock(C)) { if (C->theElements[nbr.idx].edges[nbrOtherEdge].lock(C)) { // perimeter locked; split both elements splitNeighborsLocal(longEdge, opnode, othernode, modEdge, nbrLongEdge, nbrOpnode, nbrOthernode, nbrModEdge, nbr); // and now for the tedious unlocking process C->theElements[nbr.idx].edges[nbrOtherEdge].unlock(C); } nbrModEdgeRef.unlock(C); } edges[otherEdge].unlock(C); } modEdgeRef.unlock(C); } } else { // neighbor is not local; send a special request to it pendingRequest = 1; // indicates that this element is awaiting a response mesh[nbr.cid].specialRequest(nbr.idx, myRef); } }
int Rule::countAliveNeighbors(Cell* cell, int index) { int count, i; Cell* n; count = 0; for (i = 0; i < _nSize; i++) { n = getNeighbor(cell, i); if (n->states[index] == 1) { count++; } } return count; }
/* preenche o vetor das posicoes ao redor do robo */ void encontrarAdjacentes (Position pos, Grid *grid) { int i; Position p; for (i = 0; i < 6; i++) { p = getNeighbor (pos, i); if (limiteDoMapa (p, grid->m, grid->n)) adjacentes[i] = grid->map[p.x][p.y].type; else adjacentes[i] = -1; } }
int cilk_main( std::string _inputname, std::string _coloringAlgorithm, std::string _numWorkers, std::string _ordering) { __cilkrts_set_param("nworkers", _numWorkers.c_str()); sparseRowMajor<int, int> inputGraph; // Parse the graph in .mtx or adjacency list representation. if (_inputname.find(".mtx") != string::npos) { graph<int> inter = graphFromEdges<int>(edgesFromMtxFile<int>(_inputname.c_str()), true); inputGraph = sparseFromGraph<int>(inter); } else if (_inputname.find(".edges") != string::npos) { graph<int> inter = graphFromEdges<int>(readEdgeArrayFromFile<int>((char*)_inputname.c_str()), true); inputGraph = sparseFromGraph<int>(inter); } else { graph<int> inter = graphFromEdges<int>(edgesFromGraph<int>(readGraphFromFile<int>((char*)_inputname.c_str())), true); inputGraph = sparseFromGraph<int>(inter); } // Initialize the vertex color array, and the permutation. // int* vertexColors = (int*) malloc(sizeof(int)*inputGraph.numRows); if (inputGraph.Values == NULL) { inputGraph.Values = (int*) malloc(sizeof(int)*inputGraph.numRows); } int* vertexColors = inputGraph.Values; unsigned int seed = 1234134; double beginTime = getTime(); int numColors; if (_coloringAlgorithm.compare("JP") == 0) { numColors = colorGraphJP(&inputGraph, vertexColors, _ordering, seed); } else { printf("Invalid coloring algorithm\n"); } double endTime = getTime(); for (int i = 0; i < inputGraph.numRows; i++) { for (int j = 0; j < getDegree(&inputGraph, i); j++) { int nbr = getNeighbor(&inputGraph, i, j); if (vertexColors[i] == vertexColors[nbr]) { printf("Error: vertex %d and vertex %d are neighbors and share color %d\n", i, nbr, vertexColors[i]); return -1; } } } printf("Total colors: %d\n", numColors); printf("Total time: %f\n", endTime - beginTime); return 0; }
int element::checkNeighbor(int longEdge) { elemRef nbr = getNeighbor(longEdge); if (nbr.idx == -1) { // no neighbor; on border return -1; } else { // neighbor exists int result; result = nbr.checkIfLongEdge(C, edges[longEdge]); // is longEdge shared? return result; } }
void Diamond::removeChild( ChildIndex c ) { osg::ref_ptr<Diamond> child = _c[c].get(); if ( !child.valid() ) return; // first we must merge the child (i.e. remove all of ITS children recursively). // TODO: this probably needs to queue up another merge operation with a higher priority. // that should probably happen in the mesh manager. child->merge(); // deactivate the child. it's possible that the child is in a queue somewhere. this // will prevent it from being processed after it's been removed. child->_status = INACTIVE; // remove it from its other parent as well. osg::ref_ptr<Diamond> d0 = getNeighbor( c ); if ( d0.valid() ) { ChildIndex c_d0 = d0->getIndexOfChild( child.get() ); if ( c_d0 >= 0 ) { d0->_c[c_d0] = 0L; } } // now clear out the child slot and invalidate the primitive set. this->_c[c] = 0L; // notify the common ancestry of the change if ( child->_hasGeometry ) { child->_a[QUADTREE]->dirty(); this->dirty(); } else { // probably not strictly necessary since a split() will take care of this.. gw child->_a[PARENT_L]->dirty(); child->_a[PARENT_R]->dirty(); } // zero out the child's ancestor pointers. for( AncestorIndex i = 0; i < 4; ++i ) child->_a[i] = 0L; for( ChildIndex i = 0; i < 4; ++i ) child->_c[i] = 0L; // remove the child's vertex from the VBO. _mesh->removeNode( child->_vi ); }
/* Verifica se exite algum inimigo nas posicoes adjacentes ao robo */ int inimigoAdjacente (Position pos, Grid *grid, Robot *r) { int i; Position rob_pos; Robot *rob; for (i = 0; i < 6; i++){ if (adjacentes[i] == ROBOT){ rob_pos = getNeighbor (pos, i); rob = &grid->map[rob_pos.x][rob_pos.y].object.robot; if ((rob->dir + 3)%6 == i){ return 1; } } } return 0; }
/* coloca um bloco na direção do inimigo mais proximo */ Action porBloco (Position pos, Grid *grid, Robot *r) { Direction inimigo_dir; Position inimigo; /*posicao adjacente ao robo na direcao do nimigo mais proximo*/ inimigo_dir = searchNearestRobot (grid, pos, r); if (inimigo_dir == -1 || r->obstacles == 0) return STAND; inimigo = getNeighbor (pos, inimigo_dir); if (grid->map[inimigo.x][inimigo.y].type == 0 || grid->map[inimigo.x][inimigo.y].type == 2) { if (inimigo_dir == (r->dir + 3)%6) return OBSTACLE_CENTER; if (inimigo_dir == (r->dir + 2)%6) return OBSTACLE_RIGHT; if (inimigo_dir == (r->dir + 4)%6) return OBSTACLE_LEFT; } return fastTurn (r->dir, (inimigo_dir + 3)%6); }
void Continuous::next(Cell *current, int index) { int nextIndex, state, i; double avg, wsum; nextIndex = wrapi(index + 1, 0, 2); state = current->states[index]; avg = 0.0; wsum = 0.0; for (i = 0; i < nSize(); i++ ) { avg += (getNeighbor(current, i)->states[index] * _weights[i]); wsum += _weights[i]; } avg /= wsum; current->states[nextIndex] = wrapd(avg + _add, 0.0, 1.0); }
void element::refineNeighbor(int longEdge) { elemRef nbr = getNeighbor(longEdge); // this element and the neighbor on its long edge do not share the // same longEdge if (!nbr.hasDependent(C)) { double nbrArea = nbr.getArea(C); nbr.setDependent(C, myRef.idx, myRef.cid); // set nbr's dependent to this depend = 1; // flag this element as dependent on another if (nbr.cid == myRef.cid) // nbr is local // force at least one refinement level on nbr C->theElements[nbr.idx].setTargetArea(nbrArea); else // nbr not local; tell nbr's chunk to refine nbr element mesh[nbr.cid].refineElement(nbr.idx, nbrArea); } // Note: if neighbor already has a dependent, only that dependent // will be notified when it refines. So this element must not be // labelled as dependent on another. Instead, it keeps attempting // to refine until either its neighbor has refined, or it is able // the make itself dependent on the neighbor. }
/* Retorna a acao a ser realizada quando a vida do robo eh baixa */ Action acaoSaudavel (Grid *g, Position p) { int i, j, control_dir; Position s; Robot *r = &g->map[p.x][p.y].object.robot; /*Se estiver em cima de um control point, SCORE TIME*/ if (isControlPoint (g, p) && !inimigoAdjacente (p, g, r)) { if (deveDesviar (p, g, r)) return Desviar (p, g, r); return atiraNoInimigo (g, p, r); } else { /*procura algum control point em alguam direcao do robo*/ control_dir = searchNearestControl (g, p, r); /*Caso em nenhuma direcao tem um control point livre andar em uma direcao valida, ou comeca a virar para uma direcao valida*/ if (control_dir == -1) { for(i = r->dir, j = 0; j < 6; i++,j++){ if (i >= 6) i-=6; s = getNeighbor(p,i); if(valid(s, g->m, g->n, g)) { if(i == r->dir) { return WALK; } else { return fastTurn (r->dir, i); } } } /*Se nenhuma posicao em volta eh valida, SAD TIME*/ return STAND; } /*Se encontrou um control point em alguma direcao, comeca a virar e andar em sua direcao*/ else if(control_dir == r->dir) return WALK; else { return fastTurn (r->dir, control_dir); } } }
std::size_t Model::getPointsForRoadAssumingFinished ( Board const & inBoard, Utils::Location const & inLocation, Model::Area::Area inArea ) { assert( inBoard.isRoad( inLocation, inArea ) ); std::set< Utils::Location > usedTiles; bool hasInn = false; for ( auto const & roadPiece : inBoard.getCompleteRoad( inLocation, inArea ) ) { // Add this tile to the used tiles. usedTiles.insert( Utils::Location( roadPiece.row, roadPiece.col ) ); hasInn = hasInn || inBoard.hasInn( roadPiece ); // Add its neighboring tile, even if it is not (yet) placed. PlacedRoad const neighbor = getNeighbor( roadPiece ); usedTiles.insert( Utils::Location( neighbor.row, neighbor.col ) ); } return usedTiles.size() * getPointsPerRoadTile( hasInn, true ); }
void Diamond::split() { // mark as split, and mark the primitive set as needing a refesh: _isSplit = true; if ( _hasGeometry ) { // for geometry diamonds, a split means we must regenerate this diamond // AND its quadtree ancestor. this->dirty(); _a[QUADTREE]->dirty(); } else { // for intermediate diamonds, splitting means we must rebuild each immediate parent. _a[PARENT_L]->dirty(); _a[PARENT_R]->dirty(); } _queuedForSplit = false; // check to see whether any of our neighbors are split. If a neighbor is also // split, spawn a common child. for( ChildIndex c = 0; c < _childValence; ++c ) { // debugging assertion: if ( _c[c].valid() ) { OE_WARN << "ILLEGAL STATE: diamond just split but has kids!" << std::endl; } Diamond* d0 = getNeighbor( c ); if ( d0 && d0->_isSplit ) { getOrCreateChild( c ); } } }
std::size_t Model::getPointsForCityAssumingFinished ( Board const & inBoard, Utils::Location const & inLocation, Model::Area::Area inArea ) { assert( inBoard.isCity( inLocation, inArea ) ); std::set< Utils::Location > usedTiles; std::set< Model::PlacedCity > pennants; bool hasCathedral = false; for ( auto const & cityPiece : inBoard.getCompleteCity( inLocation, inArea ) ) { // Add this tile to the used tiles. usedTiles.insert( Utils::Location( cityPiece.row, cityPiece.col ) ); hasCathedral = hasCathedral || inBoard.hasCathedral( cityPiece ); // Add its neighboring tile, even if it is not (yet) placed. PlacedRoad const neighbor = getNeighbor( cityPiece ); usedTiles.insert( Utils::Location( neighbor.row, neighbor.col ) ); } return usedTiles.size() * getPointsPerCityTile( hasCathedral, true ) + pennants.size() * getPointsPerCityPennant( hasCathedral, true ); }
DeltaHyperbolicity SimulatedAnnealing::stepImpl() { //for first step, simply calculate its delta and return the state if (_isFirstStep) { _curDelta = calculateCurrentDelta(); _isFirstStep = false; return DeltaHyperbolicity(_curDelta, _curState); } //call callback method if exists if (nullptr != _callbackFunc.get()) _callbackFunc->callback(_graph, _curState, _curDelta, _temp, false); //perform a single step node_combination_t newState; unsigned int replacedNodeIndexInState = getNeighbor(_graph, _curState, &newState); //need to calculate distances from new node to other 3 _destinationNodes.clear(); for (int i = 0; i < 4; ++i) { if (replacedNodeIndexInState != i) _destinationNodes.push_back(newState[i]); } NodeDistances NDFromReplacedNode(_graph, newState[replacedNodeIndexInState]); distance_dict_t distances = NDFromReplacedNode.getDistances(_destinationNodes); //reset new distances to a side array distance_t newNodeDistances[6]; copy(_nodeDistances, _nodeDistances+6, newNodeDistances); //start from current array, replace distances that have changed switch (replacedNodeIndexInState) { case 0: newNodeDistances[0] = distances[newState[1]->getIndex()]; newNodeDistances[1] = distances[newState[2]->getIndex()]; newNodeDistances[2] = distances[newState[3]->getIndex()]; break; case 1: newNodeDistances[0] = distances[newState[0]->getIndex()]; newNodeDistances[3] = distances[newState[2]->getIndex()]; newNodeDistances[4] = distances[newState[3]->getIndex()]; break; case 2: newNodeDistances[1] = distances[newState[0]->getIndex()]; newNodeDistances[3] = distances[newState[1]->getIndex()]; newNodeDistances[5] = distances[newState[3]->getIndex()]; break; case 3: newNodeDistances[2] = distances[newState[0]->getIndex()]; newNodeDistances[4] = distances[newState[1]->getIndex()]; newNodeDistances[5] = distances[newState[2]->getIndex()]; break; default: throw exception("Invalid index for replaced node"); } //recalculate distances of perfect matchings distance_t d1 = newNodeDistances[0] + newNodeDistances[5]; distance_t d2 = newNodeDistances[1] + newNodeDistances[4]; distance_t d3 = newNodeDistances[2] + newNodeDistances[3]; //calculate new step's new delta delta_t newDelta = HyperbolicityAlgorithms::calculateDeltaFromDistances(d1, d2, d3); //run the probability method to see if we accept the new state sa_probability_t prob = _probFunc->ProbabilityToAcceptChange(_curDelta, newDelta, _temp); bool accept = ( (static_cast<double>(rand()) / static_cast<double>(RAND_MAX)) <= prob ); //update the temperature _temp = _tempFunc->TemperatureChange(_temp, _curDelta, newDelta); //update current state if it was accepted if (accept) { _curState = newState; _curDelta = newDelta; copy(newNodeDistances, newNodeDistances+6, _nodeDistances); } return DeltaHyperbolicity(_curDelta, _curState); }
void AStar_BinaryHeap::run(HGE* hge,int _renderX,int _renderY,int startX,int startY,int endX,int endY,int heightGraph[width][length]) { int gScore[width][length]; int fScore[width][length]; int hScore[width][length]; Binary_heap openHeap; list<pNode> closeList; bool isInCloseList[width][length]; for (int i=0;i<width;i++) for (int j=0;j<length;j++) isInCloseList[i][j] = false; closeList.clear(); history.clear(); gScore[startX][startY] = 0; hScore[startX][startY] = getHScore(&map[startX][startY],&map[endX][endY]); fScore[startX][startY] = gScore[startX][startY] + hScore[startX][startY]; openHeap.push(&map[startX][startY],fScore); history.push_back(startX*length+startY); while(!openHeap.empty()) { pNode current = openHeap.front(); openHeap.pop(fScore); if(current->postionX == endX && current->postionY == endY) return; //找到路径 closeList.push_back(current); isInCloseList[current->postionX][current->postionY] = true; list<pNode> neighbor = getNeighbor(map,current); for (list<pNode>::iterator itn=neighbor.begin();itn!=neighbor.end();itn++) { if(isInCloseList[(*itn)->postionX][(*itn)->postionY]) continue; int tempGScore = gScore[current->postionX][current->postionY] + distance(current,*itn,heightGraph); if(tempGScore >= MAX_DISTANCE) continue; if(!openHeap.find((*itn))) //不在openHeap中 { (*itn)->previous = current; hScore[(*itn)->postionX][(*itn)->postionY] = getHScore(*itn,&map[endX][endY]); gScore[(*itn)->postionX][(*itn)->postionY] = tempGScore; fScore[(*itn)->postionX][(*itn)->postionY] = tempGScore + hScore[(*itn)->postionX][(*itn)->postionY]; openHeap.push((*itn),fScore); history.push_back((*itn)->postionX*length+(*itn)->postionY); // if((*itn)->postionX == endX && (*itn)->postionY == endY) // return; hge->Gfx_BeginScene(); block[(*itn)->postionX][(*itn)->postionY]->Render(_renderX+(*itn)->postionY*block_size,_renderY+(*itn)->postionX*block_size); hge->Gfx_EndScene(); } else if(tempGScore < gScore[(*itn)->postionX][(*itn)->postionY]) { (*itn)->previous = current; gScore[(*itn)->postionX][(*itn)->postionY] = tempGScore; fScore[(*itn)->postionX][(*itn)->postionY] = tempGScore + hScore[(*itn)->postionX][(*itn)->postionY]; openHeap.update((*itn),fScore); } } } }
void AStar_InsertSort_BinarySearch::run(HGE* hge,int _renderX,int _renderY,int startX,int startY,int endX,int endY,int heightGraph[width][length],insertFunc func,updateFunc upfunc) { int gScore[width][length]; int fScore[width][length]; int hScore[width][length]; for (int i=0;i<width;i++) { for (int j=0;j<length;j++) { fScore[i][j] = MAX_DISTANCE; } } vector<pNode> openList; vector<pNode> closeList; openList.push_back(&map[startX][startY]); closeList.clear(); history.clear(); gScore[startX][startY] = 0; hScore[startX][startY] = getHScore(&map[startX][startY],&map[endX][endY]); fScore[startX][startY] = gScore[startX][startY] + hScore[startX][startY]; history.push_back(startX*length+startY); while(!openList.empty()) { pNode current = removeLeastNode(openList); if(current->postionX == endX && current->postionY == endY) return; //找到路径 func(closeList,current,fScore,0); list<pNode> neighbor = getNeighbor(map,current); for (list<pNode>::iterator itn=neighbor.begin();itn!=neighbor.end();itn++) { if(findNode_BinarySearch(*itn,closeList,fScore) != -1) continue; int tempGScore = gScore[current->postionX][current->postionY] + distance(current,*itn,heightGraph); if(tempGScore >= MAX_DISTANCE) continue; int result = findNode_BinarySearch(*itn,openList,fScore); if(result == -1) //不在openList中 { (*itn)->previous = current; hScore[(*itn)->postionX][(*itn)->postionY] = getHScore(*itn,&map[endX][endY]); gScore[(*itn)->postionX][(*itn)->postionY] = tempGScore; fScore[(*itn)->postionX][(*itn)->postionY] = tempGScore + hScore[(*itn)->postionX][(*itn)->postionY]; func(openList,*itn,fScore,0); history.push_back((*itn)->postionX*length+(*itn)->postionY); // if((*itn)->postionX == endX && (*itn)->postionY == endY) // return; hge->Gfx_BeginScene(); block[(*itn)->postionX][(*itn)->postionY]->Render(_renderX+(*itn)->postionY*block_size,_renderY+(*itn)->postionX*block_size); hge->Gfx_EndScene(); } else if(tempGScore < gScore[(*itn)->postionX][(*itn)->postionY]) { (*itn)->previous = current; gScore[(*itn)->postionX][(*itn)->postionY] = tempGScore; fScore[(*itn)->postionX][(*itn)->postionY] = tempGScore + hScore[(*itn)->postionX][(*itn)->postionY]; upfunc(openList,*itn,fScore,result); } } } return; }
int cub_ob::findNeighbor(cube_directions side) { return getNeighbor(id, side); };
TEST_F(MeshLibQuadMesh, ElementNeighbors) { auto count_neighbors = [](MeshLib::Element const* const e) { unsigned count = 0; for (int i = 0; i < 4; i++) if (e->getNeighbor(i) != nullptr) count++; return count; }; auto getNeighborIndices = [this](std::size_t const i, std::size_t const j) { return std::make_pair(getNeighbor(i), getNeighbor(j)); }; auto testNeighbors = [this]( MeshLib::Element const* const e, std::size_t const i, std::size_t const j, std::pair<Indices, Indices> const& neighbors) { for (auto i_neighbor : neighbors.first) ASSERT_TRUE(e->hasNeighbor(getElement(i_neighbor, j))); for (auto j_neighbor : neighbors.second) ASSERT_TRUE(e->hasNeighbor(getElement(i, j_neighbor))); }; // Two neighbors for corner elements. testCornerElements([&](MeshLib::Element const* const e, std::size_t const i, std::size_t const j) { EXPECT_EQ(2u, count_neighbors(e)); std::pair<Indices, Indices> const ij_neighbors = getNeighborIndices(i, j); // Test the test EXPECT_EQ(1u, ij_neighbors.first.size()); EXPECT_EQ(1u, ij_neighbors.second.size()); ASSERT_TRUE(e->isBoundaryElement()); testNeighbors(e, i, j, ij_neighbors); }); // Three neighbors for boundary elements. testBoundaryElements([&](MeshLib::Element const* const e, std::size_t const i, std::size_t const j) { EXPECT_EQ(3u, count_neighbors(e)); std::pair<Indices, Indices> const ij_neighbors = getNeighborIndices(i, j); // Test the test EXPECT_EQ(3u, ij_neighbors.first.size() + ij_neighbors.second.size()); ASSERT_TRUE(e->isBoundaryElement()); testNeighbors(e, i, j, ij_neighbors); }); // Four neighbors inside mesh. testInsideElements([&](MeshLib::Element const* const e, std::size_t const i, std::size_t const j) { EXPECT_EQ(4u, count_neighbors(e)); std::pair<Indices, Indices> const ij_neighbors = getNeighborIndices(i, j); // Test the test EXPECT_EQ(2u, ij_neighbors.first.size()); EXPECT_EQ(2u, ij_neighbors.second.size()); ASSERT_FALSE(e->isBoundaryElement()); testNeighbors(e, i, j, ij_neighbors); }); }