From 1a555b900c7a5798d8f3386f3d1279934ca6647d Mon Sep 17 00:00:00 2001 From: Anna Wiggins Date: Fri, 24 Jun 2011 11:32:50 -0400 Subject: [PATCH] Split calculate_strength into a recursive and non-recursive portion - saves a lot of special checking --- gamedata.cpp | 30 +++++++++++++++++++----------- gamedata.h | 3 ++- 2 files changed, 21 insertions(+), 12 deletions(-) diff --git a/gamedata.cpp b/gamedata.cpp index d3e7d7b..c0e77db 100644 --- a/gamedata.cpp +++ b/gamedata.cpp @@ -90,18 +90,21 @@ bool GameData::add_vertex(int x, int y, int r, int colour) } -// Oh the recursive recursion! -float GameData::calculate_strength(Vertex* node, unsigned int depth, list* visited) +float GameData::calculate_strength(Vertex* node) { - if (visited == NULL) visited = new list; - visited->push_back(node); - - list all_nodes = get_colour(node->colour); + list visited; // Special case - a one-node tree just returns its own score! + list all_nodes = get_colour(node->colour); if (all_nodes.size() == 1) return (float)node->score; + return calculate_strength_r(node, 0, visited); +} + +// Oh the recursive recursion! +float GameData::calculate_strength_r(Vertex* node, unsigned int depth, list& visited) +{ // Find which vertices we need to visit from here list es = get_vertex_edges(node); list to_visit; @@ -113,19 +116,25 @@ float GameData::calculate_strength(Vertex* node, unsigned int depth, listbegin(), visited->end(), e.b) == visited->end()) + find(visited.begin(), visited.end(), e.b) == visited.end()) { to_visit.push_back(e.b); } else if (e.a == node && - find(visited->begin(), visited->end(), e.b) == visited->end()) + find(visited.begin(), visited.end(), e.b) == visited.end()) { to_visit.push_back(e.a); } } + visited.push_back(node); + // This is the base case - this node has no unvisited neighbors - if (to_visit.empty()) return (float)(node->score) / depth; + if (to_visit.empty()) + { + fprintf(stderr, "At a leaf, and score=%f, depth=%d\n", (float)node->score, depth); + return (float)(node->score) / depth; + } // Else, iterate through to_visit and visit them all, summing their // effective strengths adjusted for depth. @@ -137,9 +146,8 @@ float GameData::calculate_strength(Vertex* node, unsigned int depth, list* visited = NULL); + float calculate_strength(Vertex* node); + float calculate_strength_r(Vertex* node, unsigned int depth, list& visited); Vertex* current; Turn player;