コード例 #1
0
ファイル: search.cpp プロジェクト: crockeo/optisearch
// findSolution returns a vector of in-order moves to perform in order to reach
// a solution for a given board.
std::vector<BoardMove> findSolution(const Board b) {
    if (isSolution(b))
        return std::vector<BoardMove>();

    SearchHeap moveList([](float p1, float p2) -> float { return p2 - p1; });
    std::set<Board> seen;
    moveList.insert(0.f, std::make_tuple(b, std::vector<BoardMove>()));

    while (!moveList.isEmpty()) {
        auto pair = moveList.removeTuple();

        Board board = std::get<0>(pair.value);
        for (auto bm: board.validMoves()) {
            Board temp = board.doMove(bm);
            if (seen.find(temp) != seen.end())
                continue;
            seen.insert(temp);

            std::vector<BoardMove> moves = std::get<1>(pair.value);
            moves.push_back(bm);

            int h = heuristic(temp);
            if (h == 0)
                return moves;

            moveList.insert(pair.priority + (h / 2.f + 0.5f), std::make_tuple(temp, moves));
        }
    }

    return std::vector<BoardMove>();
}
コード例 #2
0
ファイル: solver.c プロジェクト: jneighbs/wordbrain
void recursiveSolve(TreeNode *lexTree, WBCell *cell, int solutionLen, char *solutionSoFar)
{
  // base case - if solution is of correct length and is an actual word, then print it
  if(strlen(solutionSoFar) == solutionLen){
    if(isSolution(lexTree, solutionSoFar)){
      printf("%s\n", solutionSoFar);
    }
  // else, word isn't long enough yet. Try expanding in all directions
  } else {
    int newLetterIndex = strlen(solutionSoFar);
    for(int i = 0; i < NUM_ADJACENT_CELLS; i++){
      WBCell *nextCellPtr = cell->adjacentCells[i];
      if(nextCellPtr!=NULL && !nextCellPtr->visited){
        solutionSoFar[newLetterIndex]=(*nextCellPtr).value;
        // if new direction is a valid prefix, mark current cell as visited,
        // and recurse on next cell with updated solution
        if(isPrefix(lexTree, solutionSoFar)){
          cell->visited = 1;
          recursiveSolve(lexTree, nextCellPtr, solutionLen, solutionSoFar);
        }
        // unwind after returning from recursion
        cell->visited = 0;
        solutionSoFar[newLetterIndex] = '\0';
      }
    }
  }
}
コード例 #3
0
ファイル: problem09.cpp プロジェクト: CodeManent/euler
/*
 * By working with the problem, we can express the numbers b and c based on a.
 * So we go through numbers and try to find an a that makes all other
 * restrictions fall into place.
 */
long solution() {
    //natural numbers, so a=0 isn't an accepted solution.
    for(long a = 1; ; ++a) {
        long b = getB(a);
        long c = getC(a, b);
        if(isSolution(a, b, c))
            return a*b*c;
    }

    //if it didn't find a solution return -1 as an indication of error
    return -1;
}
コード例 #4
0
ファイル: binaryprog.cpp プロジェクト: AndreG-P/appfs
void binaryprog::solveProg(){
	long power = pow(2,columns);
	for(int i = 0; i < power; i++){
		int foo[columns];
		decimalTObinary(columns, i, foo);
		dtype sum[rows];
		//check foo on feasibility by vector multiplication with the "matrix", i.e. matrix * vector
		//and then comparing the result with the vector "vector"
		for(int j = 0; j < rows; j++){
			sum[j] = 0;
			for(int k = 0; k < columns; k++){
				sum[j] += foo[k]*matrix[j][k];
			}
		}
		if(isSolution(sum))
			printSolution(foo);
	}
}
コード例 #5
0
ファイル: Problem.cpp プロジェクト: cfajitas/CSCE-420-Project
//Returns the fitness score for a N calculated from a solution
//If the number is a solution, returns the number of correct bits with a higher weight
//If the number is not a solution, returns the number of correct bits with a lower weight value
//However all weights are higher than the weight for the number of gates added later
int Problem::getFitness(bitset<30> num)
{
    if(isSolution(num))
    {
        return (limits[limits.size()]+1)*5;
    }
    else
    {
        int count=0;
        for(int i=0;i<30;++i)
        {
            if(n[i] && num[i])
            {
                ++count;
            }
        }
        return count*3;
    }
}
コード例 #6
0
ファイル: C.c プロジェクト: joaomagalhaes/lpa
int backtracking(short n, short v, short actualPrinters)
{
    int i;
    
    /* rejection test */
    if ( actualPrinters >= best)
        return 1;
    
    /* base case */
    if (isSolution(n) && actualPrinters < best){
        best = actualPrinters;
        return 1;
    }
        
    for(i = v + 1; i < n; i++)
    {
        havePrinter[i] = 1;                         /* mark as visited */
        backtracking(n, i, actualPrinters + 1);     /* recursive step */
        havePrinter[i] = 0;                         /* mark as unvisited */
    }
    return 0;
}
コード例 #7
0
bool SubgraphPlanarizerUML::doSinglePermutation(
	PlanRepLight &PG,
	int cc,
	const EdgeArray<int>  *pCost,
	Array<edge> &deletedEdges,
	UMLEdgeInsertionModule &inserter,
	minstd_rand &rng,
	int &crossingNumber)
{
	PG.initCC(cc);

	const int nG = PG.numberOfNodes();
	const int high = deletedEdges.high();

	for(int j = 0; j <= high; ++j)
		PG.delEdge(PG.copy(deletedEdges[j]));

	deletedEdges.permute(rng);

	ReturnType ret = inserter.callEx(PG, deletedEdges, pCost, nullptr);

	if(isSolution(ret) == false)
		return false; // no solution found, that's bad...

	if(pCost == nullptr)
		crossingNumber = PG.numberOfNodes() - nG;
	else {
		crossingNumber = 0;
		for(node n : PG.nodes) {
			if(PG.original(n) == nullptr) { // dummy found -> calc cost
				edge e1 = PG.original(n->firstAdj()->theEdge());
				edge e2 = PG.original(n->lastAdj()->theEdge());
				crossingNumber += (*pCost)[e1] * (*pCost)[e2];
			}
		}
	}

	return true;
}
コード例 #8
0
Module::ReturnType PlanarSubgraphModule::callAndDelete(
	GraphCopy &PG,
	const List<edge> &preferedEdges,
	List<edge> &delOrigEdges,
	bool preferedImplyPlanar)
{
	List<edge> delEdges;

	ReturnType retValue = call(PG, preferedEdges, delEdges, preferedImplyPlanar);

	if(isSolution(retValue))
	{
		ListConstIterator<edge> it;
		for(it = delEdges.begin(); it.valid(); ++it) {
			edge eCopy = *it;
	
			delOrigEdges.pushBack(PG.original(eCopy));
			PG.delCopy(eCopy);
		}
	}
		
	return retValue;
}
コード例 #9
0
Module::ReturnType SubgraphPlanarizer::doCall(PlanRep &PG,
	int cc,
	const EdgeArray<int>  &cost,
	const EdgeArray<bool> &forbid,
	const EdgeArray<unsigned int>  &subgraphs,
	int& crossingNumber)
{
	OGDF_ASSERT(m_permutations >= 1);
  
	OGDF_ASSERT(!(useSubgraphs()) || useCost()); // ersetze durch exception handling

	double startTime;
	usedTime(startTime);

	if(m_setTimeout)
		m_subgraph.get().timeLimit(m_timeLimit);

	List<edge> deletedEdges;
	PG.initCC(cc);
	EdgeArray<int> costPG(PG);
	edge e;
	forall_edges(e,PG)
		costPG[e] = cost[PG.original(e)];
	ReturnType retValue = m_subgraph.get().call(PG, costPG, deletedEdges);
	if(isSolution(retValue) == false)
		return retValue;

	for(ListIterator<edge> it = deletedEdges.begin(); it.valid(); ++it)
		*it = PG.original(*it);

	bool foundSolution = false;
	CrossingStructure cs;
	for(int i = 1; i <= m_permutations; ++i)
	{
		const int nG = PG.numberOfNodes();
		
		for(ListConstIterator<edge> it = deletedEdges.begin(); it.valid(); ++it)
			PG.delCopy(PG.copy(*it));

		deletedEdges.permute();
	
		if(m_setTimeout)
			m_inserter.get().timeLimit(
				(m_timeLimit >= 0) ? max(0.0,m_timeLimit - usedTime(startTime)) : -1);
		
		ReturnType ret;
		if(useForbid()) {
			if(useCost()) {
				if(useSubgraphs())
					ret = m_inserter.get().call(PG, cost, forbid, deletedEdges, subgraphs);
				else
					ret = m_inserter.get().call(PG, cost, forbid, deletedEdges);
			} else
				ret = m_inserter.get().call(PG, forbid, deletedEdges);
		} else {
			if(useCost()) {	
				if(useSubgraphs())
					ret = m_inserter.get().call(PG, cost, deletedEdges, subgraphs);
				else
					ret = m_inserter.get().call(PG, cost, deletedEdges);
			} else
				ret = m_inserter.get().call(PG, deletedEdges);
		}

		if(isSolution(ret) == false)
			continue; // no solution found, that's bad...
	
		if(!useCost())
			crossingNumber = PG.numberOfNodes() - nG;
		else {
			crossingNumber = 0;
			node n;
			forall_nodes(n, PG) {
				if(PG.original(n) == 0) { // dummy found -> calc cost
					edge e1 = PG.original(n->firstAdj()->theEdge());
					edge e2 = PG.original(n->lastAdj()->theEdge());
					if(useSubgraphs()) {
						int subgraphCounter = 0;
						for(int i=0; i<32; i++) {
							if(((subgraphs[e1] & (1<<i))!=0) && ((subgraphs[e2] & (1<<i)) != 0))
								subgraphCounter++;
						}
						crossingNumber += (subgraphCounter*cost[e1] * cost[e2]);
					} else
						crossingNumber += cost[e1] * cost[e2];
				}
			}
		}
		
		if(i == 1 || crossingNumber < cs.weightedCrossingNumber()) {
			foundSolution = true;
			cs.init(PG, crossingNumber);
		}
		
		if(localLogMode() == LM_STATISTIC) {
			if(m_permutations <= 200 ||
				i <= 10 || (i <= 30 && (i % 2) == 0) || (i > 30 && i <= 100 && (i % 5) == 0) || ((i % 10) == 0))
				sout() << "\t" << cs.weightedCrossingNumber();
		}
		
		PG.initCC(cc);

		if(m_timeLimit >= 0 && usedTime(startTime) >= m_timeLimit) {
			if(foundSolution == false)
				return retTimeoutInfeasible; // not able to find a solution...
			break;
		}
	}
	
	cs.restore(PG,cc); // restore best solution in PG
	crossingNumber = cs.weightedCrossingNumber();
	
	PlanarModule pm;
	OGDF_ASSERT(pm.planarityTest(PG) == true);
	
	return retFeasible;
}
コード例 #10
0
Module::ReturnType SubgraphPlanarizerUML::doCall(
	PlanRepUML           &pr,
	int                   cc,
	const EdgeArray<int> *pCostOrig,
	int                  &crossingNumber)
{
	OGDF_ASSERT(m_permutations >= 1);

	PlanarSubgraphModule   &subgraph = m_subgraph.get();
	UMLEdgeInsertionModule &inserter = m_inserter.get();

	unsigned int nThreads = min(m_maxThreads, (unsigned int)m_permutations);

	int64_t startTime;
	System::usedRealTime(startTime);
	int64_t stopTime = (m_timeLimit >= 0) ? (startTime + int64_t(1000.0*m_timeLimit)) : -1;

	//
	// Compute subgraph
	//
	if(m_setTimeout)
		subgraph.timeLimit(m_timeLimit);

	pr.initCC(cc);

	// gather generalization edges, which should all be in the planar subgraph
	List<edge> preferedEdges;
	for(edge e : pr.edges) {
		if (pr.typeOf(e) == Graph::generalization)
			preferedEdges.pushBack(e);
	}

	List<edge> delEdges;
	ReturnType retValue;

	if(pCostOrig) {
		EdgeArray<int> costPG(pr);
		for(edge e : pr.edges)
			costPG[e] = (*pCostOrig)[pr.original(e)];

		retValue = subgraph.call(pr, costPG, preferedEdges, delEdges);

	} else
		retValue = subgraph.call(pr, preferedEdges, delEdges);

	if(isSolution(retValue) == false)
		return retValue;

	const int m = delEdges.size();
	for(ListIterator<edge> it = delEdges.begin(); it.valid(); ++it)
		*it = pr.original(*it);

	//
	// Permutation phase
	//

	int seed = rand();
	minstd_rand rng(seed);

	if(nThreads > 1) {
		//
		// Parallel implementation
		//
		ThreadMaster master(
			pr, cc,
			pCostOrig,
			delEdges,
			seed,
			m_permutations - nThreads,
			stopTime);

		Array<Worker *> worker(nThreads-1);
		Array<Thread> thread(nThreads-1);
		for(unsigned int i = 0; i < nThreads-1; ++i) {
			worker[i] = new Worker(i, &master, inserter.clone());
			thread[i] = Thread(*worker[i]);
		}

		doWorkHelper(master, inserter, rng);

		for(unsigned int i = 0; i < nThreads-1; ++i) {
			thread[i].join();
			delete worker[i];
		}

		master.restore(pr, crossingNumber);

	} else {
		//
		// Sequential implementation
		//
		PlanRepLight prl(pr);

		Array<edge> deletedEdges(m);
		int j = 0;
		for(ListIterator<edge> it = delEdges.begin(); it.valid(); ++it)
			deletedEdges[j++] = *it;

		bool foundSolution = false;
		CrossingStructure cs;
		for(int i = 1; i <= m_permutations; ++i)
		{
			int cr;
			bool ok = doSinglePermutation(prl, cc, pCostOrig, deletedEdges, inserter, rng, cr);

			if(ok && (foundSolution == false || cr < cs.weightedCrossingNumber())) {
				foundSolution = true;
				cs.init(prl, cr);
			}

			if(stopTime >= 0 && System::realTime() >= stopTime) {
				if(foundSolution == false)
					return retTimeoutInfeasible; // not able to find a solution...
				break;
			}
		}

		cs.restore(pr,cc); // restore best solution in PG
		crossingNumber = cs.weightedCrossingNumber();

		OGDF_ASSERT(isPlanar(pr) == true);
	}

	return retFeasible;
}