void backTrack(int deep, State & t, int x, int y) { int i = 0; if (deep > 16) std::cout << "I'm in deep " << deep << std::endl; //std::cout << "I'm in deep : " << deep << "with : x = " << x << " and y = " << y << std::endl; //std::cout << "Waiting = " << t.waiting.data.size() << std::endl; while (i < t.waiting.data.size()) { if (t.putPiece(x, y, i)) { if (x == 15 && y == 15) std::cout << "WIN!" << std::endl; else if (x == 15) { backTrack(deep + 1, t, 0, y + 1); t.undo(0, y + 1); } else { backTrack(deep + 1, t, x + 1, y); t.undo(x + 1, y); } } i++; } }
void backTrack(TreeNode *root, int currentValue, int & maxValue){ currentValue += root->val; maxValue = max(maxValue, currentValue); if (root->left==NULL&&root->right==NULL){ return; } if (root->left != NULL){ backTrack(root->left, currentValue, maxValue); } if (root->right != NULL){ backTrack(root->right, currentValue, maxValue); } }
std::vector< std::string > wordBreak( std::string s, std::unordered_set< std::string > & dict ) { std::vector< std::string > result; //p[ i ] is a set of ints //each int k means that s[ 0, k ] can be segmented by dict //and s[ k+1, i ] can be find in dict std::vector< std::set< int > > p( s.length(), std::set< int >() ); //populate p for ( std::string::size_type i = 0; i < s.length(); ++i ) { if ( dict.find( s.substr( 0, i + 1 ) ) != dict.end() ) { p[ i ].insert( i ); } for ( std::string::size_type k = 0; k < i; ++k ) { if ( ! p[ k ].empty() && dict.find( s.substr( k + 1, i - k ) ) != dict.end() ) p[ i ].insert( k ); } } backTrack( p, s, s.length() - 1, result ); return result; }
void backTrack( const std::vector< std::set< int > > & p, const std::string & s, const int i, std::vector< std::string > & result ) { const std::set< int > & si = p[ i ]; for ( std::set< int >::const_iterator cit = si.begin(); cit != si.end(); ++cit ) { if ( *cit == i ) { result.push_back( s.substr( 0, i + 1 ) ); } else { std::string second_part( s.substr( *cit + 1, i - *cit ) ); std::vector< std::string > first_part_vec; backTrack( p, s, *cit, first_part_vec ); for ( std::vector< std::string >::const_iterator cit2 = first_part_vec.begin(); cit2 != first_part_vec.end(); ++cit2 ) { result.push_back( *cit2 + " " + second_part ); } } } }
void backTrack(string step, vector<vector<string> > &tmp, vector<string> &ladder) { ladder.push_back(step); if (map[step].empty()) tmp.push_back(ladder); else { for (string p : map[step]) backTrack(p, tmp, ladder); } ladder.pop_back(); }
void Dijkstra::calcPath(Workload& request, Graph& network, Stats& stats) { bool pathFound=false; bool exitLoop=false; Element current; // current Element Visited visited; // Visited list Priority items; // priority queue double previousCost=-1; // 1. Get initial Start node current.id=request.origin; current.cost=0; current.parent=request.origin; // TODO - possible problem... items.push(current); // 2. Loop until we have found a valid path //while (!exitLoop && !items.empty()){ while (!items.empty()){ // Pop from the priority queue current=items.top(); //std::cout<<"Current: "<<current.id<<" | Parent: "<<current.parent<< " | Goal:"<<request.destination<<std::endl; items.pop(); // remove the element from the list if (pathFound){ if(current.cost>previousCost){ exitLoop=true; // we want to exit the main loop break; } } previousCost=current.cost; if (visited.find(current.id)==visited.end()) { //visited.find(current.id)==visited.end() // Check if desired node if (current.id==request.destination){ // Found the node! pathFound=true; //std::cout<<std::endl<<request.origin<<request.destination<<std::endl; exitLoop=true; // TODO - remove me in future but currently bug when this is not here ????? map appears to be losing the parent of N for some weird reason.. } else { // push the valid children which have bandwidth and are not allready visited onto the priority queue network.begin(current.id,request.time); while (!network.end()) { pushChild(network.nextChild(),current,visited,items,network,request.time); } } // Append the current node to the visited list visited.insert(std::pair<char,Element>(current.id,current)); // be careful that the node is not allready in the visited list..possibly } } // 3. Choose one valid path at random and backtrack -> calculate and append statistics... if (pathFound){ // we have a valid path... -> backtrack to allocate resources backTrack(request.origin,request.destination,request.time ,request.timeDuration ,visited,network,stats); } else { //Path was impossible -> add blocked circuit stats.addCircuit(false); } }
void bigBackTrack(TreeNode *root){ int maxLeft = 0; int maxRight = 0; if (root->left != NULL){ backTrack(root->left, 0, maxLeft); } if (root->right != NULL){ backTrack(root->right, 0, maxRight); } res = max(res, root->val+maxLeft+maxRight); if (root->left != NULL){ bigBackTrack(root->left); } if (root->right != NULL){ bigBackTrack(root->right); } }
// Traces the path back to the first column to find where the best match starts (recursive function) int backTrack(unsigned int row, unsigned int column) { direction dir; if (column == 1) { //printf("Best fit starts at index %d\n", row-1); return row-1; } if (row == 0) return -1; dir = nw_matrix.dir[row][column]; if (dir == UP) { return backTrack(row-1, column); } else if (dir == LEFT) { return backTrack(row, column-1); } else if (dir == DIAG) { return backTrack(row-1, column-1); } return -1; }
int main() { std::cout << "Hello boys !!!" << std::endl; PieceList test; test.load("doom.txt"); State init; init.loadPieces(test); backTrack(0, init, 0, 0); system("Pause"); }
/* return the ans type and set ansmap if exist */ int Sudoku::backTrack() { int row, col; /* locate hole and check finish */ /* recursive out condition */ bool finished=true; for(row=0; row<size; row++) { for(col=0; col<size; col++) if(map[row][col]==0) { //--cout << row*size+col << endl; finished = false; break; } if(finished==false) break; } //cout << "locate hole in " << row << ", " << col << endl; if(finished) { ans++; memcpy(ansmap, map, sizeof(ansmap)); return 1; } /* set candidate */ bool ncan[10]={0}; setncan(row, col, ncan); /* backtracking */ for(int test=1; test<=9; test++) { if(ncan[test] == false) { //cout << "test " << test << endl; map[row][col] = test; backTrack(); if(ans>1) return 2; /* remark for next */ map[row][col] = 0; } } //cout << "try all test number" << endl; if(!ans) return 0; else if(ans==1) return 1; }
void backTrack(int sum,int n,vector<int> &temp){ if(sum>n)return; if(sum==n){ for(int i=0;i<temp.size()-1;++i) cout<<temp[i]; cout<<temp[temp.size()-1]<<endl; return; } for(int i=1;i<=n;++i){ temp.push_back(i); backTrack(sum+i,n,temp); temp.pop_back(); } }
int findEndPos(int** table, int** workTable, int rows, int cols) { int* shortestEndPosArr = findShortestEndPos(workTable, rows, cols); if(shortestEndPosArr == NULL) { return 1; //error! } else { int ith = shortestEndPosArr[0]; int jth = shortestEndPosArr[1]; backTrack(table, workTable, rows, cols, ith, jth); } return 0; }
vector<string> backTrack(string& s, vector<vector<int> >& spaceIdx, int idx) { vector<string> res; if (idx <= 0) {res.push_back(""); return res;} for (int i = 0; i < spaceIdx[idx].size(); i++) { string str = s.substr(spaceIdx[idx][i], idx - spaceIdx[idx][i]); vector<string> subRes = backTrack(s, spaceIdx, spaceIdx[idx][i]); for (int j = 0; j < subRes.size(); j++) { if (subRes[j] != "") subRes[j] = subRes[j] + " " + str; else subRes[j] = str; res.push_back(subRes[j]); } } return res; }
vector<string> wordBreak(string s, unordered_set<string> &dict) { vector<string> res; if (dict.size() == 0) return res; vector<vector<int> > spaceIdx; spaceIdx.resize(s.size() + 1); spaceIdx[0].push_back(-1); for (int i = 1; i <= s.size(); i++) { for (int j = 0; j < i; j++) { if (spaceIdx[j].size() && dict.count(s.substr(j, i - j))) { spaceIdx[i].push_back(j); } } } return backTrack(s, spaceIdx, s.size()); }
int totalNQueens(int n) { int* layout = new int[n]; layout[0] = 0; int col = 0, count = 0; while(true){ if(isSafe(layout, col)) { col++; if(col < n) layout[col] = 0; else count++; } else { layout[col]++; } if(!backTrack(layout, &col, n)) break; } delete layout; return count; }
vector<vector<string> > solveNQueens(int n) { vector<vector<string> > res; if(n == 0) return res; int* layout = new int[n]; layout[0] = 0; int col = 0, count = 0; while(true){ if(isSafe(layout, col)) { col++; if(col < n) layout[col] = 0; else addLayout(res, layout, n); } else { layout[col]++; } if(!backTrack(layout, &col, n)) break; } delete layout; return res; }
bool Sudoku::answer(int mode){ //mode 0: solve //mode 1: check int i, j, last, tmp[9][9]; bool onlySol=true; if(mode==1) for(i=0; i<9; i++) for(j=0; j<9; j++) tmp[i][j]=grid[i][j]; initPsb(0); while(remain>0){ last=remain; PSB(); if(remain==last) break; } if(remain>0) onlySol=backTrack(); if(mode==0) printf("%d\n", onlySol? 1: 2); else for(i=0; i<9; i++) for(j=0; j<9; j++) grid[i][j]=tmp[i][j]; return onlySol; }
/* no -> 0, unique -> 1 and map, multi -> 2 */ void Sudoku::Solve() { /*Check multiple solutions*/ if(multiCheck()) { cout << "2" << endl; return; } /* Check -1 */ if(!checkDonCare()) { cout << "0" << endl; return; } /* wrong map check by base rule*/ for(int i=0; i<size; i++) for(int j=0; j<size; j++) if(!ok(i, j, map[i][j])) wrongMap = true; if(wrongMap) { cout << "0" << endl; return; } /* normal check */ int type = backTrack(); if(type==0) cout << "0" << endl; else if(type==1) printMap('s'); else cout << "2" << endl; }
bool kekulizeWorker(RWMol &mol, const INT_VECT &allAtms, boost::dynamic_bitset<> dBndCands, boost::dynamic_bitset<> dBndAdds, INT_VECT done, unsigned int maxBackTracks) { INT_DEQUE astack; INT_INT_DEQ_MAP options; int lastOpt = -1; boost::dynamic_bitset<> localBondsAdded(mol.getNumBonds()); // ok the algorithm goes something like this // - start with an atom that has been marked aromatic before // - check if it can have a double bond // - add its neighbors to the stack // - check if one of its neighbors can also have a double bond // - if yes add a double bond. // - if multiple neighbors can have double bonds - add them to a // options stack we may have to retrace out path if we chose the // wrong neighbor to add the double bond // - if double bond added update the candidates for double bond // - move to the next atom on the stack and repeat the process // - if an atom that can have multiple a double bond has no // neighbors that can take double bond - we made a mistake // earlier by picking a wrong candidate for double bond // - in this case back track to where we made the mistake int curr; INT_DEQUE btmoves; unsigned int numBT = 0; // number of back tracks so far while ((done.size() < allAtms.size()) || (astack.size() > 0)) { // pick a curr atom to work with if (astack.size() > 0) { curr = astack.front(); astack.pop_front(); } else { for (int allAtm : allAtms) { if (std::find(done.begin(), done.end(), allAtm) == done.end()) { curr = allAtm; break; } } } done.push_back(curr); // loop over the neighbors if we can add double bonds or // simply push them onto the stack INT_DEQUE opts; bool cCand = false; if (dBndCands[curr]) { cCand = true; } int ncnd; // if we are here because of backtracking if (options.find(curr) != options.end()) { opts = options[curr]; CHECK_INVARIANT(opts.size() > 0, ""); } else { RWMol::ADJ_ITER nbrIdx, endNbrs; boost::tie(nbrIdx, endNbrs) = mol.getAtomNeighbors(mol.getAtomWithIdx(curr)); while (nbrIdx != endNbrs) { // ignore if the neighbor has already been dealt with before if (std::find(done.begin(), done.end(), static_cast<int>(*nbrIdx)) != done.end()) { ++nbrIdx; continue; } // ignore if the neighbor is not part of the fused system if (std::find(allAtms.begin(), allAtms.end(), static_cast<int>(*nbrIdx)) == allAtms.end()) { ++nbrIdx; continue; } // if the neighbor is not on the stack add it if (std::find(astack.begin(), astack.end(), static_cast<int>(*nbrIdx)) == astack.end()) { astack.push_back(rdcast<int>(*nbrIdx)); } // check if the neighbor is also a candidate for a double bond // the refinement that we'll make to the candidate check we've already // done is to make sure that the bond is either flagged as aromatic // or involves a dummy atom. This was Issue 3525076. // This fix is not really 100% of the way there: a situation like // that for Issue 3525076 but involving a dummy atom in the cage // could lead to the same failure. The full fix would require // a fairly detailed analysis of all bonds in the molecule to determine // which of them is eligible to be converted. if (cCand && dBndCands[*nbrIdx] && (mol.getBondBetweenAtoms(curr, *nbrIdx)->getIsAromatic() || mol.getAtomWithIdx(curr)->getAtomicNum() == 0 || mol.getAtomWithIdx(*nbrIdx)->getAtomicNum() == 0)) { opts.push_back(rdcast<int>(*nbrIdx)); } // end of curr atoms can have a double bond ++nbrIdx; } // end of looping over neighbors } // now add a double bond from current to one of the neighbors if we can if (cCand) { if (opts.size() > 0) { ncnd = opts.front(); opts.pop_front(); Bond *bnd = mol.getBondBetweenAtoms(curr, ncnd); bnd->setBondType(Bond::DOUBLE); // remove current and the neighbor from the dBndCands list dBndCands[curr] = 0; dBndCands[ncnd] = 0; // add them to the list of bonds to which have been made double dBndAdds[bnd->getIdx()] = 1; localBondsAdded[bnd->getIdx()] = 1; // if this is an atom we previously visted and picked we // simply tried a different option now, overwrite the options // stored for this atoms if (options.find(curr) != options.end()) { if (opts.size() == 0) { options.erase(curr); btmoves.pop_back(); if (btmoves.size() > 0) { lastOpt = btmoves.back(); } else { lastOpt = -1; } } else { options[curr] = opts; } } else { // this is new atoms we are trying and have other // neighbors as options to add double bond store this to // the options stack, we may have made a mistake in // which one we chose and have to return here if (opts.size() > 0) { lastOpt = curr; btmoves.push_back(lastOpt); options[curr] = opts; } } } // end of adding a double bond else { // we have an atom that should be getting a double bond // but none of the neighbors can take one. Most likely // because of a wrong choice earlier so back track if ((lastOpt >= 0) && (numBT < maxBackTracks)) { // std::cerr << "PRE BACKTRACK" << std::endl; // mol.debugMol(std::cerr); backTrack(mol, options, lastOpt, done, astack, dBndCands, dBndAdds); // std::cerr << "POST BACKTRACK" << std::endl; // mol.debugMol(std::cerr); numBT++; } else { // undo any remaining changes we made while here // this was github #962 for (unsigned int bidx = 0; bidx < mol.getNumBonds(); ++bidx) { if (localBondsAdded[bidx]) { mol.getBondWithIdx(bidx)->setBondType(Bond::SINGLE); } } return false; } } // end of else try to backtrack } // end of curr atom atom being a cand for double bond } // end of while we are not done with all atoms return true; }
/* ------------------------------------- * LBFGS * IN * func: Function to be minimized. * nRow: Number of rows (length) of x. * N_max: Maximum number of CG iterates. * TOL: Minimum size for gradient of f. * OUT * x: Local minimum of func. * ------------------------------------- */ double * SLM_LBFGS(double (* func)(double*, int), int nRow, int m, double TOL, int N_max, int verbose){ // Variable declaration. double **s, **y; double *x, *grad, *p, *x_new, *grad_new; double alpha, norm_grad0; int i, k, MAX_ITER, exploredDataPoints; // Space allocation. x = (double *)malloc(nRow * sizeof(double)); s = (double **)malloc((nRow*m) * sizeof(double)); y = (double **)malloc((nRow*m) * sizeof(double)); // Initialize x. for(i = 0; i < nRow; i++){ x[i] = ((double) rand() / INT_MAX) ; } // Stochastic Mode if(stocMode){ exploredDataPoints = 0; //printf("\nRUNNING STOCASTIC MODE\n"); SAMPLE = rand() % (int)(MAX_FILE_ROWS * sampProp); create_sample(0); exploredDataPoints += SAMPLE; } // Until Convergence or MAX_ITER. MAX_ITER = 6e6; grad = gradCentralDiff(func, x, nRow); // Update s, y. k = 0; // Initial norm of gradient. norm_grad0 = norm(grad, nRow); while(norm(grad, nRow) > TOL*(1 + norm_grad0) && ((run_logistic*exploredDataPoints + ((1 - run_logistic)*k)) < MAX_ITER)){ if(stocMode){ printf("\nRUNNING STOCASTIC MODE\n"); SAMPLE = rand() % (int)(MAX_FILE_ROWS * sampProp); create_sample(k); exploredDataPoints += SAMPLE; } // p = -Hgrad(f) if(k > 0){ p = vProd(findHSLM(func, x, s, y, nRow, m, k, N_max), -1, nRow); }else{ p = vProd(grad, -1, nRow); } // Alpha that statifies Wolfe conditions. alpha = backTrack(func, x, p, nRow, verbose); x_new = vSum(x, vProd(p, alpha, nRow), nRow); //imprimeTit("X_NEW"); //imprimeMatriz(x_new, 1, nRow); grad_new = gradCentralDiff(func, x_new, nRow); //imprimeTit("GRAD_NEW"); //imprimeMatriz(grad_new, 1, nRow); // Update s, y. updateSY(s, y, vProd(p, alpha, nRow), vSum(grad_new, vProd(grad, -1, nRow), nRow), m, k); // ---------------- PRINT ------------------- // if(verbose){ if(stocMode){ printf("\n ITER = %d; f(x) = %.10e ; " "||x|| = %.10e ; ||grad|| = %.10e ; " "||p|| = %.10e ; sTy = %.10e ; " "alpha = %.10e; explored data points = %d; precision = %fl ", k, func(x, nRow), norm(x, nRow), norm(grad, nRow), norm(p, nRow), dotProd(s[(int)min(k , (m - 1))], y[(int)min(k , (m - 1))], nRow), alpha, exploredDataPoints, class_precision(x, nRow, 0)); }else{ printf("\n ITER = %d; f(x) = %.10e ; " "||x|| = %.10e ; ||grad|| = %.10e ; " "||p|| = %.10e ; sTy = %.10e ; " "alpha = %.10e", k, func(x, nRow), norm(x, nRow), norm(grad, nRow), norm(p, nRow), dotProd(s[(int)min(k , (m - 1))], y[(int)min(k , (m - 1))], nRow), alpha); } } // ---------------- PRINT ------------------- //y // Update k, x, grad. x = x_new; grad = grad_new; k = k + 1; } free(grad); free(s); free(y); return x; }
void backTrack(int** table, int** workTable, int rows, int cols, int ith, int jth) { int neighbors[8]; neighbors[0] = workTable[ith - 1][jth -1]; neighbors[1] = workTable[ith - 1][jth]; neighbors[2] = workTable[ith - 1][jth +1]; neighbors[3] = workTable[ith][jth -1]; neighbors[4] = workTable[ith][jth +1]; neighbors[5] = workTable[ith + 1][jth -1]; neighbors[6] = workTable[ith + 1][jth]; neighbors[7] = workTable[ith + 1][jth +1]; int i; int min = neighbors[0]; int minPos = 0; for(i = 1; i < 8; i++) { if((neighbors[i] < min || min < 0) && neighbors[i] >= 0) { min = neighbors[i]; minPos = i; } } int j; if(min == start) { return; } else { switch(minPos) { case 0: i = ith - 1; j = jth - 1; break; case 1: i = ith -1; j = jth; break; case 2: i = ith - 1; j = jth + 1; break; case 3: i = ith; j = jth - 1; break; case 4: i = ith; j = jth + 1; break; case 5: i = ith + 1; j = jth - 1; break; case 6: i = ith + 1; j = jth; break; case 7: i = ith + 1; j = jth + 1; break; } table[i][j] = path; workTable[i][j] = obst; backTrack(table, workTable, rows, cols, i, j); //recursive call to find the full path } }
vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) { vector<vector<string> > ans, ansTmp; unordered_set<string> s1, s2, s3; s1.insert(beginWord); s2.insert(endWord); int i, j, w, width = beginWord.length(); char ch; string str, tmp; bool endFlag = false; while (!s1.empty() && !s2.empty() && !endFlag) { for (auto item = s1.begin(); item != s1.end(); ++item) wordList.erase(*item); for (auto item = s1.begin(); item != s1.end(); ++item) { str = tmp = *item; for (i = 0; i < width; ++i) { ch = str[i]; for (j = 0; j < 26; ++j) { str[i] = 'a' + j; if (wordList.find(str) != wordList.end()) { s3.insert(str); map[str].push_back(tmp); if (s2.find(str) != s2.end()) endFlag = true; } } str[i] = ch; } } s1.swap(s3); s1.swap(s2); s3.clear(); } vector<string> ladder; for (auto item = s1.begin(); item != s1.end(); ++item) { if (s2.find(*item) != s2.end()) { ansTmp.clear(); backTrack(*item, ansTmp, ladder); if (ansTmp.size() == 1) {reverse(ansTmp[0].begin(), ansTmp[0].end()); return ansTmp;} for (i = 0; i < ansTmp.size() - 1; ++i) { for (j = i + 1; j < ansTmp.size(); ++j) { if (ansTmp[i].back() == endWord && ansTmp[j].back() == beginWord) { ans.push_back(vector<string>()); for (w = ansTmp[j].size() - 1; w > 0 ; --w) { ans.back().push_back(ansTmp[j][w]); } for (w = 0; w < ansTmp[i].size(); ++w) { ans.back().push_back(ansTmp[i][w]); } } else if (ansTmp[j].back() == endWord && ansTmp[i].back() == beginWord){ ans.push_back(vector<string>()); for (w = ansTmp[i].size() - 1; w > 0 ; --w) { ans.back().push_back(ansTmp[i][w]); } for (w = 0; w < ansTmp[j].size(); ++w) { ans.back().push_back(ansTmp[j][w]); } } } } } } return ans; }
Vector2D getRange(int index,int holeNo,int pNo) { Vector2D range; Vector2D t1; t1.X = coin[index].X; t1.Y = coin[index].Y; Vector2D dir = subtract(&t1,&holes[holeNo]); normalize(&dir); Vector2D aimPos = backTrack(dir,&coin[index],&striker); double m = dir.Y / dir.X; double c = aimPos.Y - m * aimPos.X; if(pNo == 0) { double high = (-2.1 - c)/ m; if(high > 1.91) { high = 1.91; } if(high < -1.91) { high = -1.91; } if(t1.X < -1.91) { t1.X = -1.909; } if(t1.X > 1.91) { t1.X = 1.911; } range.X = t1.X; range.Y = high; return range; }else if(pNo == 1) { double high = -2.1f * m + c; if(high > 1.91) { high = 1.91; } if(high < -1.91) { high = -1.91; } if(t1.Y < -1.91) { t1.Y = -1.909; } if(t1.Y > 1.91) { t1.Y = 1.911; } range.X = t1.Y; range.Y = high; return range; }else if(pNo == 2) { double high = (2.1 - c)/ m; if(high > 1.91) { high = 1.91; } if(high < -1.91) { high = -1.91; } if(t1.X < -1.91) { t1.X = -1.909; } if(t1.X > 1.91) { t1.X = 1.911; } range.X = t1.X; range.Y = high; return range; }else if(pNo == 3) { double high = 2.1f * m + c; if(high > 1.91) { high = 1.91; } if(high < -1.91) { high = -1.91; } if(t1.Y < -1.91) { t1.Y = -1.909; } if(t1.Y > 1.91) { t1.Y = 1.911; } range.X = t1.Y; range.Y = high; return range; } }
void AI(double *X, double *Y, double *velX,double *velY) { C_SHOT tWork; if(singlePlayerMode == 1 || bot == 1) { reset_1(&tWork); Vector2D t1; Vector2D strPos; int y = 0; int temporary = 0; for(y = 0;y < 5 && temporary == 0; y++){ if(coinsLeft == 2 && f_queenPocketed == 0 && isQueenOnBoard == 1) { y=2; temporary = 1; } int iP= 0; int z=0; for (z = 0; z < totalCoins ; z++){ double sepn = magnitude(coin[y].X - coin[z].X, coin[y].Y - coin[z].Y); if((sepn <= coin[y].radius + coin[z].radius + 0.01f) && coin[z].visible == 1 && z != y) { iP = 1; } } if(coin[y].visible == 1){ t1.X = coin[y].X; t1.Y = coin[y].Y; int loc = 0; for(loc = 0;loc < 4; loc++){ Vector2D dir = subtract(&t1,&holes[loc]); normalize(&dir); Vector2D aimPos = backTrack(dir,&coin[y],&striker); Vector2D range = getRange(y,loc,0); double temp = range.Y; strPos.Y = -2.1; strPos.X = temp; if(sweepTest1(t1,holes[loc],y) == 0){ Vector2D vel1 = computeVelocity(t1,holes[loc],NULL,&coin[y],t1); if((coin[y].Y < -2.1 && loc >= 2) || (coin[y].Y > -2.1 && loc >= 0 && loc < 2)){ if((loc % 2 == 0 && loc < 2) || ((loc % 2 == 1 && loc >= 2)) ){ for( temp = range.Y; temp >= range.X ; temp -= 0.001f) { int ii =0; double sepi = 0; int invalidPosition= 0; for (ii = 0; ii < totalCoins ; ii++){ sepi = magnitude(strPos.X - coin[ii].X, strPos.Y - coin[ii].Y); if((sepi < striker.radius + coin[ii].radius) && coin[ii].visible == 1) { invalidPosition = 1; } } if((sweepTest2(strPos,aimPos,y) == 0) && (invalidPosition == 0)) { break; } strPos.X = temp; } }else { for( temp = range.Y; temp >= range.X ; temp += 0.001f) { int ii =0; double sepi = 0; int invalidPosition= 0; for (ii = 0; ii < totalCoins ; ii++){ sepi = magnitude(strPos.X - coin[ii].X, strPos.Y - coin[ii].Y); if((sepi < striker.radius + coin[ii].radius) && coin[ii].visible == 1) { invalidPosition = 1; } } if((sweepTest2(strPos,aimPos,y) == 0) && (invalidPosition == 0)) { break; } strPos.X = temp; } } Vector2D dir2 = subtract(&strPos,&aimPos); normalize(&dir2); double acc = dotProduct(&dir,&dir2); if(acc < 0) acc=-acc; Vector2D fVel = computeVelocity(strPos,aimPos,&coin[y],&striker,vel1); if((acc >= tWork.accuracy && acc > 0) || (coinsLeft == 2 && f_queenPocketed == 0 && isQueenOnBoard == 1)) { tWork.accuracy = -acc; tWork.X= strPos.X; tWork.Y= strPos.Y; tWork.vX = fVel.X; tWork.vY = fVel.Y; if(coinsLeft == 2 && f_queenPocketed == 0 && isQueenOnBoard == 1){ break; } } } } } } } } double err = 0; if(AI_level == 1){ err = (rand() % 100) / 1000.0f + 0.01f; }else if(AI_level == 2) { err = (rand() % 1000) / 10000.0f + 0.001f; } *X = tWork.X + err; *Y = tWork.Y; *velX = tWork.vX; *velY = tWork.vY; }
void combinationSum11(int n){ assert(n>0); vector<int> temp; backTrack(0,n,temp); }
void cdPath(const char *path){ char goHere[MaxPathLength]; char *home = getenv("HOME"); char *current = get_current_dir_name(); int currLength = strlen(current); int homeLength = strlen(home); int length = strlen(path); int i; if(strlen(path) == 1){ if(path[0] == '~'){ chdir(home); return; } else if(path[0] == '/'){ chdir("/"); return; } } if(strlen(path) == 2){ if(path[0] == '~' && path[1] == '/'){ chdir(home); return; } if(path[0] == '.' && path[1] == '.'){ backTrack(current, 1); chdir(whatever); return; } } if(path[0] == '/'){ char changeHere[length]; for(i = 0; i < length; i++){ changeHere[i] = path[i]; } chdir(changeHere); return; } if(path[0] == '~' && path[1] == '/'){ if(length > 3){ if(path[2] == '.' && path[3] == '.'){ //backtrack // ~/../abc backTrack(home,1); printf("!%s!", whatever); // printf(strlen(whatever)); int counter = 0; while(whatever[counter] != '\0'){ counter++; } char changeHere0[counter+2]; for(i = 0; i < counter; i++){ changeHere0[i] = whatever[i]; printf("i: %d\n", i); printf("VALUE: %c\n", changeHere0[i]); printf("NG val: %c\n", whatever[i]); } // printf("count: %d", counter); // for(i = 0; i < length-4; i++){ // changeHere0[counter+i] = path[4+i]; // } printf("count: %d", counter); printf("HEREERERE: %s!", changeHere0); printf("AFTER"); } else{ char changeHere2[length-1+homeLength]; for(i = 0; i < homeLength; i++){ changeHere2[i] = current[i]; } for(i = 0; i < length; i++){ changeHere2[i+homeLength] = path[i+1]; } chdir(changeHere2); return; } } } if(path[0] == '.' && path[1] == '/'){ char changeHere3[length-1+currLength]; for(i = 0; i < currLength; i++){ changeHere3[i] = current[i]; } for(i = 0; i < length; i++){ changeHere3[i+currLength] = path[i+1]; } chdir(changeHere3); return; } //../../abc if(path[0] == '.' && path[1] == '.' && path[2] == '/'){ if(strlen(path) > 4){ if(path[3] == '.' && path[4] == '.'){ backTrack(current, 2); if(strlen(path) < 7){ chdir(whatever); return; } else{ // ../../abc int counts = 0; while(whatever[counts] != '\0'){ counts++; } char changeHere6[counts+length]; for(i = 0; i < counts; i++){ changeHere6[i] = whatever[i]; } for(i = 0; i < length; i++){ changeHere6[i+counts] = path[5+i]; } chdir(changeHere6); return; } } } backTrack(current, 1); int count = 0; while(whatever[count] != '\0'){ count++; } char changeHere5[length+count]; for(i = 0; i < count; i++){ changeHere5[i] = whatever[i]; } for(i = 0; i < length; i++){ changeHere5[i+count] = path[2+i]; } chdir(changeHere5); } if(path[0] != '/' && path[0] != '~' && path[0] != '.'){ char changeHere4[length+currLength]; for(i = 0; i < currLength; i++){ changeHere4[i] = current[i]; } changeHere4[currLength] = '/'; for(i = 0; i < length; i++){ changeHere4[i+currLength+1] = path[i]; } chdir(changeHere4); return; } }
pair<vector<unsigned long>,vector<unsigned long>> SeqGraphAlignment::alignStringToGraphFast() { //if (typeid(sequence).name() != "string") { // cerr << "Invalid Type" << endl; // return; //} unsigned long l1 = graph->numberOfNodes; unsigned long l2 = sequence.length(); unordered_map<unsigned long, unsigned long> nodeIDtoIndex; unordered_map<unsigned long, unsigned long> nodeIndexToID; nodeIndexToID[-1] = (unsigned long) -1; auto nodes = graph->nodes; unsigned long index = 0; for (auto nodeID : graph->nodeOrder) { nodeIDtoIndex[nodeID] = index; nodeIndexToID[index] = nodeID; index++; } // for (map<int, Node *>::iterator it = nodes.begin(); it != nodes.end(); it++) { // nodeIDtoIndex[it->second->ID] = it->first; // nodeIndexToID[it->first] = it->second->ID; // } vector<vector<long>> scores(l1 + 1, vector<long>(l2 + 1)); if (globalAlign) { for (int i = 1; i < l2 + 1; i++) { scores[0][i] = openGapValue + (i - 1) * extendGapValue; } nodes = graph->nodes; index = 0; for (auto nodeID : graph->nodeOrder) { auto mIter = graph->nodes[nodeID]; auto prevIndexs = prevIndices(mIter, nodeIDtoIndex); scores[0][0] = openGapValue - extendGapValue; long best = scores[prevIndexs.front() + 1][0]; for (auto lIter = prevIndexs.begin(); lIter != prevIndexs.end(); lIter++) { best = max(best, scores[*lIter + 1][0]); } scores[index + 1][0] = best + extendGapValue; scores[0][0] = 0; index++; } } vector<vector<unsigned long>> backStrIdx(l1 + 1, vector<unsigned long>(l2 + 1)); vector<vector<unsigned long>> backGrphIdx(l1 + 1, vector<unsigned long>(l2 + 1)); vector<char> seqvec; copy(sequence.begin(), sequence.end(), back_inserter(seqvec)); vector<vector<long>> insertCost(l1 + 1, vector<long>(l2 + 1, this->openGapValue)); // memset(*insertCost, this->openGapValue, sizeof (int) * (l1+1) * (l2+1)); vector<vector<long>> deleteCost(l1 + 1, vector<long>(l2 + 1, this->openGapValue)); // memset(deleteCost, this->openGapValue, sizeof (int) * (l1+1) * (l2+1)); // fill(&insertCost[0][0], &insertCost[l1][l2], this->openGapValue); // fill(&deleteCost[0][0], &deleteCost[l1][l2], this->openGapValue); vector<bool> inserted(l2 + 1, false); vector<long> insertScore(l2 + 2, 0); char gbase; vector<unsigned long> predecessors; vector<long> matchPoints, deleteScore(l2), matchScore(l2); vector<unsigned long> bestDelete(l2), bestMatch(l2); vector<bool> deleted; index = 0; for (auto nodeID : graph->nodeOrder) { auto it = nodes[nodeID]; gbase = it->base; predecessors = prevIndices(it, nodeIDtoIndex); matchPoints = matchScoreVec(gbase, seqvec); deleteScore.clear(); for (int j = 1; j < l2 + 1; j++) { deleteScore.push_back(scores[predecessors.front() + 1][j] + deleteCost[predecessors.front() + 1][j]); matchScore[j - 1] = scores[predecessors.front() + 1][j - 1] + matchPoints[j - 1]; } auto fill_value = predecessors.front() + 1; fill(bestDelete.begin(), bestDelete.end(), fill_value); fill(bestMatch.begin(), bestMatch.end(), fill_value); for (auto it2 = next(predecessors.begin()); it2 != predecessors.end(); it2++) { vector<long> newDeleteScore; vector<long> newMatchScore; for (int j = 1; j < l2 + 1; j++) { newDeleteScore.push_back(scores[*it2 + 1][j] + deleteCost[*it2 + 1][j]); newMatchScore.push_back(scores[*it2 + 1][j - 1] + matchPoints[j - 1]); } for (int i = 0; i < l2; i++) { bestDelete[i] = newDeleteScore[i] > deleteScore[i] ? *it2 + 1 : bestDelete[i]; bestMatch[i] = newMatchScore[i] > matchScore[i] ? *it2 + 1 : bestMatch[i]; } for (int i = 0; i < l2; i++) { deleteScore[i] = max(newDeleteScore[i], deleteScore[i]); matchScore[i] = max(newMatchScore[i], matchScore[i]); } } deleted.clear(); for (unsigned long i = 0; i < l2; i++) { deleted.push_back(deleteScore[i] > matchScore[i]); } for (unsigned long j = 1; j < l2 + 1; j++) { scores[index + 1][j] = deleteScore[j - 1] >= matchScore[j - 1] ? deleteScore[j - 1] : matchScore[j - 1]; backGrphIdx[index + 1][j] = deleted[j - 1] ? bestDelete[j - 1] : bestMatch[j - 1]; backStrIdx[index + 1][j] = deleted[j - 1] ? j : j - 1; deleteCost[index + 1][j] = deleted[j - 1] ? extendGapValue : deleteCost[index + 1][j]; } //insertions fill(inserted.begin(), inserted.end(), false); for (int j = 0; j < l2 + 1; j++) { insertScore[j] = scores[index + 1][j] + insertCost[index + 1][j]; } for (unsigned long j = 0; j < l2; j++) { if (insertScore[j] > scores[index + 1][j + 1]) { scores[index + 1][j + 1] = insertScore[j]; insertCost[index + 1][j + 1] = extendGapValue; backStrIdx[index + 1][j + 1] = j; inserted[j + 1] = true; insertScore[j + 1] = scores[index + 1][j + 1] + insertCost[index + 1][j + 1]; } } for (int j = 1; j < l2 + 1; j++) { if (inserted[j]) { insertCost[index + 1][j] = extendGapValue; deleteCost[index + 1][j] = openGapValue; backGrphIdx[index + 1][j] = index + 1; } } if (!globalAlign) { for (int j = 0; j < l2; j++) { backGrphIdx[nodeID + 1][j] = scores[nodeID + 1][j] > 0 ? backGrphIdx[nodeID + 1][j] : (unsigned long) -1; backStrIdx[nodeID + 1][j] = scores[nodeID + 1][j] > 0 ? backStrIdx[nodeID + 1][j] : (unsigned long) -1; scores[nodeID + 1][j] = max(scores[nodeID + 1][j], 0L); } } index++; } return backTrack(l1, l2, scores, backStrIdx, backGrphIdx, nodeIndexToID); }
pair<vector<unsigned long>,vector<unsigned long>> SeqGraphAlignment::alignStringToGraphSimple() { unsigned long l1 = graph->numberOfNodes; unsigned long l2 = sequence.length(); unordered_map<unsigned long, unsigned long> nodeIDtoIndex; unordered_map<unsigned long, unsigned long> nodeIndexToID; nodeIndexToID[-1] = (unsigned long) -1; auto nodes = graph->nodes; unsigned long index = 0; for (auto nodeID : graph->nodeOrder) { nodeIDtoIndex[nodeID] = index; nodeIndexToID[index] = nodeID; index++; } vector<vector<long>> scores(l1 + 1, vector<long>(l2 + 1)); if (globalAlign) { for (unsigned long i = 1; i < l2 + 1; i++) { scores[0][i] = openGapValue + (i - 1) * extendGapValue; } nodes = graph->nodes; index = 0; for (auto nodeID : graph->nodeOrder) { auto mIter = graph->nodes[nodeID]; auto prevIndexs = prevIndices(mIter, nodeIDtoIndex); scores[0][0] = openGapValue - extendGapValue; long best = scores[prevIndexs.front() + 1][0]; for (auto lIter = prevIndexs.begin(); lIter != prevIndexs.end(); lIter++) { best = max(best, scores[*lIter + 1][0]); } scores[index + 1][0] = best + extendGapValue; scores[0][0] = 0; index++; } } vector<vector<unsigned long>> backStrIdx(l1 + 1, vector<unsigned long>(l2 + 1)); vector<vector<unsigned long>> backGrphIdx(l1 + 1, vector<unsigned long>(l2 + 1)); // map<tuple<int,int>,int> insertCost, deleteCost; int insertCost[l1 + 1][l2 + 1]; // memset(*insertCost, this->openGapValue, sizeof (int) * (l1+1) * (l2+1)); int deleteCost[l1 + 1][l2 + 1]; // memset(deleteCost, this->openGapValue, sizeof (int) * (l1+1) * (l2+1)); fill_n(*insertCost, (l1+1) * (l2+1), this->openGapValue); fill_n(*deleteCost, (l1+1) * (l2+1), this->openGapValue); char gbase; vector<char> seqvec; copy(sequence.begin(), sequence.end(), back_inserter(seqvec)); index = 0; for (auto nodeID : graph->nodeOrder) { auto it = nodes[nodeID]; gbase = it->base; unsigned long index2=0; for (vector<char>::iterator it3 = seqvec.begin(); it3 != seqvec.end(); it3++) { long best1=scores[index+1][index2] + insertCost[index+1][index2]; unsigned long best2=index+1; unsigned long best3=index2; string best4="INS"; auto predIndex = prevIndices(it, nodeIDtoIndex); for (auto it2 = predIndex.begin(); it2 != predIndex.end(); it2++) { if( best1 < (scores[*it2+1][index2] + matchScore(*it3,gbase)) || best2 < (*it2+1) || best3 < index2 ) { best1 = (scores[*it2+1][index2] + matchScore(*it3,gbase)); best2 = (*it2+1); best3 = index2; best4 = "MATCH"; } if( best1 < (scores[*it2+1][index2+1] + deleteCost[*it2+1][index2]) || best2 < (*it2+1) || best3 < index2 ) { best1 = (scores[*it2+1][index2+1] + deleteCost[*it2+1][index2]); best2 = (*it2+1); best3 = index2+1; best4 = "DEL"; } } scores[index+1][index2+1] = best1; backGrphIdx[index+1][index2+1] = best2; backStrIdx[index+1][index2+1] = best3; if(best4 == "INS") { insertCost[index+1][index2+1] = extendGapValue; } else if(best4 == "DEL") { deleteCost[index+1][index2+1] = extendGapValue; } } } return backTrack(l1, l2, scores, backStrIdx, backGrphIdx, nodeIndexToID); }