void ChallengeStatus::save(UTFWriter& writer) { writer << L" <" << m_data->getId(); if (isSolved(RaceManager::DIFFICULTY_HARD)) writer << L" solved=\"hard\"/>\n"; else if (isSolved(RaceManager::DIFFICULTY_MEDIUM)) writer << L" solved=\"medium\"/>\n"; else if (isSolved(RaceManager::DIFFICULTY_EASY)) writer << L" solved=\"easy\"/>\n"; else writer << L" solved=\"none\"/>\n"; } // save
void Puzzle::solve() { //runs all the solving algorithms in the //order that we found most efficient. for (int k = 0; k < 100; k++) { for (int i = 0; i < 9; i++) { rows[i].reduceByNumbers(); } for (int i = 0; i < 9; i++) { cols[i].reduceByNumbers(); } for (int i = 0; i < 9; i++) { boxes[i].reduceByNumbers(); } for (int j = 0; j < 9; j++) { rows[j].reduceByCells(); cols[j].reduceByCells(); boxes[j].reduceByCells(); } if (isSolved()) { k = 100; } // printPrettyPuzzle(); //for fun debug // cin.get() //for viewing pleasure } }
bool Tobias::solve( size_t max, size_t slot, size_t student ) { //std::clog << slot << "," << student << "..." << std::endl; if( student == getNames().size() ) { slot++; student = 0; } if( avaiableSlots() == 0 || slot >= slots() ) { //std::cerr << (*this) << std::endl; return isSolved( max ); } //std::clog << "!" << !slotFull( slot, max ) << std::endl; //std::clog << ">" << getChoices().at( student * slots() + slot ) << std::endl; //std::clog << "+" << !isStudentScheduled( student ) << std::endl; if( getReference().at( slot ) && !slotFull( slot, max ) && getChoices().at( student * slots() + slot ) && !isStudentScheduled( student ) ) { schedule[ student * slots() + slot ] = true; //std::clog << "Trying schedule[" << student << "," << slot << "] = true..." << std::endl; if( solve( max, slot, student + 1 ) ) { return true; } schedule[ student * slots() + slot ] = false; } // else { return solve( max, slot, student + 1 ); // } return false; }
int MtxLP::fixSolution(int kind, bool tmp){ if (!isSolved()) return 0; strvec cnames = getColNames(kind); for (strvec::iterator i = cnames.begin(); i != cnames.end(); i++) fix(*i, getColValue(*i), tmp); return cnames.size(); }
bool validSudoko(int g[N][N]) { int row,col; int i; if(isSolved(g, &row, &col)) return true; for(i=1;i<=N;i++) { if(isSafe(g,row, col, i)) { g[row][col] = i; if(validSudoko(g)) return true; g[row][col]=0; } } return false; }
void Scene1202::update() { Scene::update(); if (_isPuzzleSolved) { if (!isSoundPlaying(3)) leaveScene(0); } else if (_counter == 0 && isSolved()) { _clickedIndex = 0; SetMessageHandler(&Scene1202::hmSolved); setGlobalVar(V_TNT_DUMMY_BUILT, 1); _palette->copyToBasePalette(_paletteData); _palette->startFadeToPalette(24); playSound(3); _isPuzzleSolved = true; } else if (_clickedIndex >= 0 && _counter == 0) { // Swap TNT positions int destIndex = kScene1202Table[_clickedIndex]; sendMessage(_asTntItems[_clickedIndex], 0x2001, getSubVar(VA_TNT_POSITIONS, destIndex)); sendMessage(_asTntItems[destIndex], 0x2001, getSubVar(VA_TNT_POSITIONS, _clickedIndex)); int temp = getSubVar(VA_TNT_POSITIONS, destIndex); setSubVar(VA_TNT_POSITIONS, destIndex, getSubVar(VA_TNT_POSITIONS, _clickedIndex)); setSubVar(VA_TNT_POSITIONS, _clickedIndex, temp); _counter = 2; _clickedIndex = -1; playSound(_soundToggle ? 1 : 2); _soundToggle = !_soundToggle; } }
void interfaceLoop() { Puzzle *puzzle = NULL; char command = '\0'; showSolution = false; createDirectionKeys(); createOptionKeys(); do { puzzle = createPuzzle(getPuzzleSize()); shuffleCount = getShuffleCount(); shufflePuzzle(puzzle, shuffleCount); showSolution = false; while( !isSolved(puzzle) ){ printHeader(); printPuzzle(puzzle); command = getNextCommand(puzzle); if(command == INVERT_KEY) { puzzle->inverted = (puzzle->inverted) ? false : true; invertSolution(puzzle); setDirectionVectors(puzzle); } else if(command == SOLVE_KEY) showSolution = (showSolution) ? false : true; else if(command == QUIT_KEY || command == RESTART_KEY) break; else applyDirection(puzzle, getData(directionKeys, command)); } if( isSolved(puzzle) ) { printPuzzle(puzzle); printWinner(); } destroyPuzzle(&puzzle); } while(command == RESTART_KEY); destroyOptionKeys(); destroyDirectionKeys(); }
void MtxLP::getSolution(stomap* sol, strvec q, int kind, bool withzeroes) const{ if (!isSolved()) return; for (strvec::iterator i = q.begin(); i != q.end(); i++){ string name = *i; double coef = getColValue(name); if (withzeroes || !is_zero(coef)) (*sol)[name] = coef; } }
void SudokuProblem::solve() { // Wenn das Sudoku noch nicht geloest wurde: if (!isSolved()) { // Bereite das Sudoku vor (löst ganz einfache Sudokus bereits) solvePreparation(); // Starte rekursives Lösen (für schwierigere Sudokus) solveRecursion(0, 0); // Ausgabe der Informationen zur Lösung des Sudokus: if (isSolved()) { cout << "Sudoku Problem wurde geloest: " << endl; print(); cout << "Es waren " << recursionCounter << " wiederholte rekursive Aufrufe noetig." << endl; } else { cout << "Das Sudoku Problem wurde nicht geloest." << endl; } } }
double QPsolver_qpOASES::getObjVal( ) const { if ( isUnbounded( ) == true ) return -INFTY; if ( ( isSolved( ) == false ) || ( qp == 0 ) ) return INFTY; return qp->getObjVal( ); }
bool Sudoku::solve() { if(!hasMemory()) return false; try { while(!isSolved()) { if(!fillInBigSquares() && !fillInRows() && !fillInColumns()) return false; } } catch(InvalidSudoku &err) { std::cerr << err.what() << "\n"; } return true; }
int MtxLP::fixSupport(int kind, bool tmp){ int rv = 0; if (!isSolved()) return 0; strvec cnames = getColNames(kind); for (strvec::iterator i = cnames.begin(); i != cnames.end(); i++){ if (is_zero(getColValue(*i))){ block(*i, tmp); rv++; } } return rv; }
/** After the slice is done rotating, replace the original cubes with the new cubes by changing the colors */ void updateCubes() { for (int i=0; i<CUBES_PER_PLANE; i++) memcpy(colors[lastRotationCubesBefore[i]],newCubeColors[i],sizeof(colors[0])); for (int i=0; i<CUBES_PER_PLANE; i++) { addRotation(lastRotationCubesBefore[i],lastRotationAxis,lastRotationWasClockwise); positions[lastRotationCubesBefore[i]] = lastRotationCubesAfter[i]; } finishedRotating = true; if (isSolved()) std::cout << "Rubik's cube solved!" << std::endl; }
void SplitLP::minExchangeSets(solvec& solutions, stomap* obj, int dir, long nmax){ strvec externals = getExternals(); strvec txs(externals.size());// - obj->size()); strvec::iterator ti = txs.begin(); stomap::iterator oend = obj->end(); for (strvec::iterator it = externals.begin(); it != externals.end(); ++it){ string xname = *it; string txname = getTransporterName(xname, dir); stomap::iterator jt = obj->find(xname); if (jt != oend){ double coef = jt->second; coef /= this->vmax; fix(txname, coef, true, txname + "_mxs"); } else if (dir > 0){ fix(txname, 0, true); } *ti++ = get_opp_name(txname); } setObjDir(false); setLenObjective(txs, true); strvec itxs = get_int_names(txs); long i = 0; while(i < nmax){ stomap conv; stomap sol; Solve(true); getConversion(&conv); if (!isSolved()) break; getSolution(&sol, itxs, INT, false); if (!conv.empty()){ i++; if (dir < 0){ minimiseInput(&conv, txs); setLenObjective(txs, true); } solutions.push_back(conv); } if (i < nmax) cutSolution(&sol, true); } // cleanTmpRows(); }
void solve(unsigned short* sudoku, int recursionLevel) { do { boolean couldSimplify = simplify(sudoku, recursionLevel); // if(recursionLevel > 0 && !couldSimplify) // return; if(isSolved(sudoku)) return; } while( guess(sudoku, recursionLevel+1) ); }
void guessSolution(puzzle *g, int level) { if (level > 2) return; // Don't allow recursion beyond 2 to happen. if (isSolved(*g)) return; // Don't recurse if solved for (int x=0; x<9; x++) for (int y=0; y<9; y++) if (g->cell[x][y][0] == 0) // Look for cells that aren't solved. { bool movePossible = false; // Keep track of possible moves for (int j=1; j<10; j++) { puzzle t; copyPuzzle(*g, &t); // Copy puzzle so we keep original intact if (t.cell[x][y][j] == true) // See if j is a candidate number { movePossible = true; // We have a valid move to try t.cell[x][y][0] = j; // Set cell to candidate value solveGrid(&t); // Try solving grid if (isSolved(t)) // If solved, { copyPuzzle(t, g); // Copy solved puzzle back to master return; // and return! } else { guessSolution(&t, level+1); // Recurse back if not yet solved if (isSolved(t)) // If that did the trick { copyPuzzle(t, g); // Copy back to master return; // And return! } } } } if (movePossible == false) // If no valid moves are found return; // Dead end. Return... } }
bool Sudoku::solveBacktracking( int row, int col ) { if( col >= size() ) { row += 1; col = 0; } if( row >= size() ) { return isSolved(); } if( !isWritable( row, col ) ) { return solveBacktracking( row, col + 1 ); } for( int v = 0; v < size(); v++ ) { // check if value v is possible: bool isPossibleValue = true; // row: for( int c = 0; isPossibleValue && c < size(); c++ ) { if( (*this)( row, c ) == v ) { isPossibleValue = false; } } // col: for( int r = 0; isPossibleValue && r < size(); r++ ) { if( (*this)( r, col ) == v ) { isPossibleValue = false; } } // block: int r = row / k * k; int c = col / k * k; for( int i = 0; isPossibleValue && i < k; i++ ) { for( int j = 0 ; isPossibleValue && j < k; j++ ) { if( (*this)( r + i, c + j ) == v) { isPossibleValue = false; } } } if(isPossibleValue) { set( row, col, v ); // recurse: if( solveBacktracking( row, col + 1 ) ) { return true; } set( row, col, -1); } } return false; }
bool solveCindy(char *board, int holePosition, int boardSize, int *numSteps) { levelOfDepth++; if(debug) { for(int i = 0; i < levelOfDepth; i++) printf("%s", "| "); } printf("%s\n", board); if(isSolved(board, boardSize)) return true; *numSteps += 1; for(int i = 0; i < 4; i++) { int candidateMove = getMoveByIndex(i, holePosition); if(canMove(board, holePosition, boardSize, candidateMove)) { board[holePosition] = board[candidateMove]; board[candidateMove] = '.'; if(solveCindy(board, candidateMove, boardSize, numSteps)) return true; board[candidateMove] = board[holePosition]; board[holePosition] = '.'; levelOfDepth--; if(debug) { for(int i = 0; i < levelOfDepth; i++) printf("%s", "| "); } printf("%s\n", board); } } return false; }
returnValue QPsolver_qpOASES::getVarianceCovariance( DMatrix &H, DMatrix &var ) { if ( qp == 0 ) return ACADOERROR( RET_INITIALIZE_FIRST ); if ( (bool)isSolved( ) == false ) return ACADOERROR( RET_QP_NOT_SOLVED ); qpOASES::returnValue returnvalue; qpOASES::SolutionAnalysis analyser ; uint NV, NC ; uint run1, run2 ; NV = qp->getNV(); NC = qp->getNC(); double *Var = new double[(2*NV+NC)*(2*NV+NC)]; double *PrimalDualVar = new double[(2*NV+NC)*(2*NV+NC)]; for( run1 = 0; run1 < (2*NV+NC)*(2*NV+NC); run1++ ) Var[run1] = 0.0; for( run1 = 0; run1 < NV; run1++ ) for( run2 = 0; run2 < NV; run2++ ) Var[run1*(2*NV+NC)+run2] = H(run1,run2); returnvalue = analyser.getVarianceCovariance( qp, Var, PrimalDualVar ); if( returnvalue != qpOASES::SUCCESSFUL_RETURN ) { delete[] Var ; delete[] PrimalDualVar; return ACADOERROR(RET_QP_NOT_SOLVED); } var.init( NV, NV ); for( run1 = 0; run1 < NV; run1++ ) for( run2 = 0; run2 < NV; run2++ ) var( run1, run2 ) = PrimalDualVar[run1*(2*NV+NC)+run2]; delete[] Var ; delete[] PrimalDualVar; return SUCCESSFUL_RETURN; }
bool BoardGenerator::solve(int round){ lastSolveRound = round; while (singleSolveMove(round)){ if (isSolved()) return true; if (isImpossible()) return false; } int nextGuessRound = round+1; int nextRound = round+2; for (int guessNumber=0; guess(nextGuessRound, guessNumber); guessNumber++){ if (isImpossible() || !solve(nextRound)){ rollbackRound(nextRound); rollbackRound(nextGuessRound); } else { return true; } } return false; }
// This sets the first empty cell to the least possible value and returns a Square with row // and col of cell it edits. This function is used inside the recursiveSolver() function to // make guesses systematically. // If the first empty cell has no possible values the Square that is returned will have -1 for // row and col. Square Sudoku::makeGuess() { Square saved; saved.row = -1; saved.col = -1; // Only make a guess on valid unsolved boards. if( isSolvable() && !isSolved() ) { // Find the first empty cell and save it. for( int r = 0; r < 9; r++ ) { for( int c = 0; c < 9; c++ ) { if( 0 == cell[r][c] ) { saved.row = r; saved.col = c; break; } } if( -1 != saved.row ) break; } // Loop through values 1-9 for( int v = 1; v <= 9; v++ ) { // Try to assign the value to the saved empty cell // Exit once it's set. // This assigns the lowest possible value. if( set( saved.row, saved.col, v ) ) { break; } } } return saved; }
int main(int argc, char *argv[]) { Maze maze; readMazeFromFile(&maze, "maze3D.txt"); unsigned int solution_count = 13; Direction solution[] = {EAST, NORTH, EAST, SOUTH, EAST, NORTH, UP, WEST, WEST, NORTH, NORTH, DOWN, SOUTH}; Position position, goal; getPosition(maze, &position); getGoal(maze, &goal); printf("Current position: "); printPositionWithNewline(position); printf("Goal: "); printPositionWithNewline(goal); printf("\n"); printMaze(maze); printPossibleMoves(maze); printf("\n"); for (int i=0; i < solution_count; i++) { if (makeMove(&maze, solution[i]) == 1) { if (isSolved(maze)) { printf("Maze solved!\n"); printPathWithNewline(maze.path); break; } else { printf("Movement successful, maze not solved.\n"); } } else { printf("Error moving from: "); printPosition(maze.pos); printf (" to %s\n", convertDirectionToString(solution[i])); } } return EXIT_SUCCESS; }
bool SudokuProblem::solveRecursion(int row, int col) { recursionCounter++; // Wenn das Soduko bereits gelöst ist, gebe true zurück if (isSolved()) return true; // Gehe zum ersten leeren Feld: // Solange wir nicht alle Zeilen durchlaufen haben // und wir nicht auf einem leeren Feld sind while (row < 9 && sudoku[row][col] != 0) { // Gehe ein Feld weiter col++; // Wenn wir am Ende einer Zeile angekommen sind if (col == 9) { // Gehe zur nächsten Zeile row++; col = 0; } } // Probiere die Werte 1-9 im leeren Feld aus: // Durchlaufe die Werte 1-9 for (int i = 1; i <= 9; i++) { // Setze den aktuellen Wert in das aktuelle Feld sudoku[row][col] = i; // Prüfe ob sich daraus ein gültiges Sudoku ergibt if (checkRow(row) && checkCol(col) && checkBlock(row, col) && solveRecursion(row, col)) { return true; } } // Wenn bis hier kein true zurück gegeben wurde: // Wert zurücksetzen und erneut aufrufen lassen. sudoku[row][col] = 0; return false; }
void Tile::swapButtons(QPushButton *button, QPushButton *button_neighbour) { button->hide(); button_neighbour->setText(button->text()); button->setText("16"); button_neighbour->show(); button_neighbour->setFocus(); if (isRunning) { Moves++; updateMoves(); } if (isRunning && isSolved()) { isRunning = 0; switch (QMessageBox::information(this, "Solved!", "Hooray, you solved it!\nShuffle again?", "&Yes","&No")) { case 0: Shuffle(); default: break; } } }
int BoardGenerator::countSolutions(int round, bool limitToTwo){ while (singleSolveMove(round)){ if (isSolved()){ rollbackRound(round); return 1; } if (isImpossible()){ rollbackRound(round); return 0; } } int solutions = 0; int nextRound = round+1; for (int guessNumber=0; guess(nextRound, guessNumber); guessNumber++){ solutions += countSolutions(nextRound, limitToTwo); if (limitToTwo && solutions >=2){ rollbackRound(round); return solutions; } } rollbackRound(round); return solutions; }
int main(){ Border smallBorder, bigBorder, blankContent, topBorder, bottomBorder; setBorder(smallBorder, VERTICALDOUBLELINECHAR, HORIZONTALLINECHAR, CENTRECHAR, VERTICALDOUBLELINECHAR, VERTICALDOUBLELINECHAR); setBorder(bigBorder, LEFTMIDDLECHAR, HORIZONTALDOUBLELINECHAR, HORIZONTALDOUBLELINECHAR, DOUBLECENTRECHAR, RIGHTMIDDLECHAR); setBorder(blankContent, VERTICALDOUBLELINECHAR, BLANK, VERTICALLINECHAR, VERTICALDOUBLELINECHAR, VERTICALDOUBLELINECHAR); setBorder(topBorder, TOPLEFTCORNERCHAR, HORIZONTALDOUBLELINECHAR, HORIZONTALDOUBLELINECHAR, TOPMIDDLECHAR, TOPRIGHTCORNERCHAR); setBorder(bottomBorder, BOTTOMLEFTCORNERCHAR, HORIZONTALDOUBLELINECHAR, HORIZONTALDOUBLELINECHAR, BOTTOMMIDDLECHAR, BOTTOMRIGHTCORNERCHAR); DoubleIntArrPointer *possibleResult; possibleResult = new DoubleIntArrPointer[SIZE]; int finalSolution [SIZE][SIZE]; int possibleLength [SIZE][SIZE]; setUpGiven(finalSolution); setUpPossible(possibleResult); setUpGivenPossibility(possibleResult, finalSolution, possibleLength); setUpChecks(possibleResult, finalSolution, possibleLength); while(!isSolved(possibleLength)){ enterSequential(possibleResult, finalSolution, possibleLength); updateTrickColumn(possibleResult, finalSolution, possibleLength); updateTrickRow(possibleResult, finalSolution, possibleLength); for(int i = 1; i <= 9; i++){ enterBox(possibleResult, finalSolution, possibleLength, i); enterNumber(possibleResult, finalSolution, possibleLength, i, ROWMODE); enterNumber(possibleResult, finalSolution, possibleLength, i, COLMODE); updateTrickRowAdvanced(possibleResult, finalSolution, possibleLength, i); updateTrickColAdvanced(possibleResult, finalSolution, possibleLength, i); } } for (int bigVerBox = 0; bigVerBox < VERBOX; bigVerBox++){ for (int smallVerBox = 0; smallVerBox < VERBOX; smallVerBox++){ if(smallVerBox == 0){ if (bigVerBox == 0){ drawBorder(topBorder); }else{ drawBorder(bigBorder); } }else{ drawBorder(smallBorder); } for (int bigBox = 0; bigBox < HORBOX; bigBox++){ for (int smallBox = 0; smallBox < HORBOX; smallBox++){ if(smallBox == 0){ if(bigBox != 0){ printf("%c", blankContent.secondBorder); }else{ printf("%c", blankContent.firstBorder); } }else{ printf("%c", blankContent.innerBorder); } printf("%d", finalSolution[bigBox*3 + smallBox][bigVerBox*3 + smallVerBox]); } } printf("%c\n", blankContent.endBorder); } } drawBorder(bottomBorder); }
int main() { printf("Project Euler - Problem 96:\n" "By solving fifty Sudoku puzzles, find the sum of the 3-digit numbers found in the top left corner of each solution grid.\n\n"); puzzle sudoku[50]; // Struct for all 50 Sudoku grids and candidates bool verbose = false; // Read in game grids nameFile = fopen ("problem_096.txt", "rt"); int grid = -1, row = -1, col = 0, ch; bool skip = false; while((ch = fgetc(nameFile))) { if (ch == EOF) break; if (ch == 'G') { skip = true; row = -1; grid++; } if (ch == '\n') { row++; col = 0; skip = false; continue; } if (skip == true) continue; ch -= '0'; // Convert from ASCII to DEC sudoku[grid].cell[row][col][0] = ch; col++; } fclose(nameFile); // Solve grid by grid int numSolved = 0; for (int i=0; i<50; i++) { if (verbose == true) printf("Grid: %d\n", i+1); if (verbose == true) printPuzzle(sudoku[i]); // Simple deduction first solveGrid(&sudoku[i]); if (isSolved(sudoku[i])) { numSolved++; if (verbose == true) printPuzzle(sudoku[i]); continue; } // Cycle through options looking for answers guessSolution(&sudoku[i], 1); if (isSolved(sudoku[i])) { numSolved++; if (verbose == true) printPuzzle(sudoku[i]); continue; } if (verbose == true) printf("Unsolved...\n"); if (verbose == true) printPuzzle(sudoku[i]); } // Add up top, left-most numbers int sum = 0; for (int i=0; i<50; i++) { int num = sudoku[i].cell[0][0][0]*100; num += sudoku[i].cell[0][1][0] * 10; num += sudoku[i].cell[0][2][0]; sum += num; if (verbose == true) printf("Grid %2d: %d\n", i+1, num); } printf("Solved %d out of %d.\n", numSolved, 50); printf("Sum: %d\n", sum); return 0; }
void CStarCrosshairs::selectStar(int index, CVideoSurface *surface, CStarField *starField, CStarMarkers *markers) { if (_entryIndex >= 0) { // There are existing selected stars already if (_entryIndex == _matchIndex) { // All the stars selected so far have been matched. Only allow // a selection addition if not all three stars have been found if (!isSolved()) { // Don't allow the most recent match or the one before // it to be re-selected (while they are locked/matched) if (_positions[index] != _entries[_entryIndex]) { if (_entryIndex == 1) { // 2 stars are matched if (_positions[index] == _entries[_entryIndex - 1]) return; } surface->lock(); // Draw crosshairs around the selected star CSurfaceArea surfaceArea(surface); drawStar(index, &surfaceArea); surface->unlock(); // Copy the star into the list of selected ones ++_entryIndex; CStarPosition &newP = _entries[_entryIndex]; newP = _positions[index]; // Set up a marker in the main starfield for that same star const CBaseStarEntry *starP = starField->getDataPtr(newP._index1); markers->addStar(starP); } } } else if (_entryIndex == _matchIndex + 1) { // There is a most recently selected star that has not yet been matched. // So we allow the user to reselect it to remove the selection, or shift // the selection to some other star if (_positions[index] == _entries[_entryIndex]) { // Player has selected the most recent star // Remove the crosshairs for the previously selected star surface->lock(); CSurfaceArea surfaceArea(surface); eraseCurrent(&surfaceArea); surface->unlock(); // Decrement number of selections --_entryIndex; // Call the markers addStar method, which will remove the existing marker const CBaseStarEntry *starP = starField->getDataPtr(_positions[index]._index1); markers->addStar(starP); } else { // Player has selected some other star other than the most recent // Remove/Add it if it is not one of the other star(s) already matched // Check that it is not a previously star and don't remove it if it is for (int i = 0; i < _entryIndex; ++i) { if (_positions[index] == _entries[i]) return; } // Erase the prior selection and draw the new one surface->lock(); CSurfaceArea surfaceArea(surface); eraseCurrent(&surfaceArea); drawStar(index, &surfaceArea); surface->unlock(); // Remove the old selection from the starfield markers const CBaseStarEntry *starP; starP = starField->getDataPtr(_entries[_entryIndex]._index1); markers->addStar(starP); // Add the new selection to the markers list starP = starField->getDataPtr(_positions[index]._index1); markers->addStar(starP); // Copy the newly selected star's details into our selections list CStarPosition &newP = _entries[_entryIndex]; newP = _positions[index]; } } } else { // Very first star being selected // Draw crosshairs around the selected star surface->lock(); CSurfaceArea surfaceArea(surface); drawStar(index, &surfaceArea); surface->unlock(); // Copy the star into the list of selected ones ++_entryIndex; const CStarPosition &srcPos = _positions[index]; CStarPosition &destPos = _entries[_entryIndex]; destPos = srcPos; // Set up a marker in the main starfield for that same star const CBaseStarEntry *starP = starField->getDataPtr(destPos._index1); markers->addStar(starP); } }
// I recommend seeing the recursive form first. // This is exactly the same algorithm, but in a loop, using // a stack instead of recursion, for efficiency. bool solveCindyLoop(char *board, int holePosition, int boardSize, int *numSteps) { Stack *indexStack = stack_init(); Stack *holeStack = stack_init(); // The current move index int cuMoveIndex = 0;//, cuHolePosition = holePosition; bool deadEnd = false; do { if(debug) { for(int i = 0; i < levelOfDepth; i++) printf("%s", "| "); } printf("%s\n", board); if(isSolved(board, boardSize)) { while(!stack_is_empty(indexStack)) stack_pop(indexStack); stack_destroy(indexStack); while(!stack_is_empty(holeStack)) stack_pop(holeStack); stack_destroy(holeStack); return true; } int candidateMove = getMoveByIndex(cuMoveIndex, holePosition); while(!canMove(board, holePosition, boardSize, candidateMove)) { cuMoveIndex += 1; if(cuMoveIndex > 3) { deadEnd = true; break; } candidateMove = getMoveByIndex(cuMoveIndex, holePosition); } if(!deadEnd) { board[holePosition] = board[candidateMove]; board[candidateMove] = '.'; stack_push(indexStack, (void*) cuMoveIndex); stack_push(holeStack, (void*) holePosition); levelOfDepth += 1; cuMoveIndex = 0; holePosition = candidateMove; *numSteps += 1; } else { do { cuMoveIndex = (int)stack_pop(indexStack); holePosition = (int)stack_pop(holeStack); levelOfDepth -= 1; int thatMove = getMoveByIndex(cuMoveIndex, holePosition); board[thatMove] = board[holePosition]; board[holePosition] = '.'; } while(cuMoveIndex == 3 && !stack_is_empty(indexStack)); if(cuMoveIndex < 3) { deadEnd = false; cuMoveIndex += 1; } } } while(!deadEnd); stack_destroy(indexStack); stack_destroy(holeStack); return false; }
int Player1::alphaBeta (int depth, int alpha, int beta, bool MAXplayer) { int heuristic = 0; bool go = false; int temp; char winner = 'N'; // 'N' for NULL go = isSolved(winner); // get heur info if (depth == 3 || go ) // or node is a terminal node { heuristic = getHeuristic(depth, winner, !(MAXplayer)); return heuristic;// value of the terminal game tree node } if (MAXplayer) //for each child of node { for (int p = 0; p < 19; p++){ for (int q = 0; q < 19; q++) { if (pOneBoard[p][q] == 'E' && playerDetected(p,q)) { pOneBoard[p][q] = 'P'; // make move on board temp = alphaBeta(depth+1, alpha, beta, !(MAXplayer)); // total recursive calls boardsExamined++; // -- maxmax start- //if (temp > alpha) alpha = temp; //a = max() //pOneBoard[p][q] = 'E'; //unmake move on board // -- maxmax end--- // -- ab code start- if (temp < alpha) alpha = temp; //alpha = max() if (beta <= alpha) { pOneBoard[p][q] = 'E';break; } else pOneBoard[p][q] = 'E'; // -- ab cod end --- }}} return alpha; // α } else //MINplayer //for each child of node { for (int p = 0; p < 19; p++){ for (int q = 0; q < 19; q++) { if (pOneBoard[p][q] == 'E' && playerDetected(p,q)) { pOneBoard[p][q] = 'T'; // make move on board temp = alphaBeta(depth+1, alpha, beta, !(MAXplayer)); // total recursive calls boardsExamined++; // -- maxmax start- //if (temp > beta) beta = temp; // β := max() //pOneBoard[p][q] = 'E'; //unmake move on board // -- maxmax end--- // -- ab code start- if (temp > beta) beta = temp; // β := min() if (beta <= alpha) { pOneBoard[p][q] = 'E'; break; } else pOneBoard[p][q] = 'E'; // -- ab cod end --- }}} return beta; // β } }