Exemplo n.º 1
0
/** NOT USED (Simulated Annealing is Superior) **/
Puzzle PuzzleGenerator::HillClimbing(double timelimit, Puzzle p)
{
	// Function that uses hillclimbing algorithm to find best value puzzle.
	// Returns best puzzle found after timelimit or local max when if it is found before time limit

	Puzzle bestPuzzle = p;

	// Keep track of the time so we don't exceed it.
	Timer t;
	t.StartTimer();

	while (t.GetElapsedTime() < timelimit-0.1)
	{
		// Generate all successors of bestPuzzle
		vector<Puzzle> successors;
		bestPuzzle.GetAllSuccessors(successors);

		Puzzle bestSuccessor = successors[0];

		// Determine highest valued successor and save as new best puzzle
		for (vector<Puzzle>::size_type i = 0; i != successors.size(); i++)
		{
			if (successors[i].GetValue() > bestSuccessor.GetValue())
			{
				bestSuccessor = successors[i];
			}
		}

		// Make sure that best successor is better than its parent (bestPuzzle), save it as the new best puzzle, and loop.
		if (bestSuccessor.GetValue() > bestPuzzle.GetValue())
		{
			bestPuzzle = bestSuccessor;
		}
		else 
		{
			// If it's not better, we found a local maximum. Save it and
			return bestPuzzle;
		}
	}

	printf("time limit reached\n");
	return bestPuzzle;
}
Exemplo n.º 2
0
/** NOT USED (Example Code provided by professor) **/
Puzzle PuzzleGenerator::RandomWalk(double timelimit)
{
	// A very simple function that start at a random configuration and keeps randomly modifying it
	// until it hits the time limit. Returns the best solution found so far.

	Puzzle p(nRows, nColumns, minVal, maxVal);	// Generate a random puzzle with the specified values.
	
	// Keep track of the best puzzle found so far (and its value).
	Puzzle bestPuzzle = p;			
	int bestValue = p.GetValue();
	
	// Keep track of the time so we don't exceed it.
	Timer t;
	t.StartTimer();
	
	// Loop until we hit the time limit.
	while (t.GetElapsedTime() < timelimit-0.1)	// To make sure that we don't exceed the time limit, we stop just before we hit the time limit.
	{
		// Generate a successor of p by randomly changing the value of a random cell 
		// (since we are doing a random walk, we just replace p with its successor).
		p = p.GetRandomSuccessor();	
		
		// Update the current best solution.
		if (p.GetValue() > bestValue)	// Calling GetValue() for the first time is costly
										// since the puzzle has to be evaluated first.
		{
			bestValue = p.GetValue();	// Calling it a second time simply returns the value that was computed before.
			bestPuzzle = p;
		}
	}
	
	return bestPuzzle;
	
	// The following code is not executed in this function. It exists just as an example for getting all the successors of a puzzle.
	vector<Puzzle> successors;
	bestPuzzle.GetAllSuccessors(successors);
}