COOPY » Guide
version 0.6.5
|
00001 #include <coopy/Mover.h> 00002 #include <coopy/Dbg.h> 00003 00004 #include <algorithm> 00005 00006 using namespace std; 00007 using namespace coopy::cmp; 00008 00009 #include <stdio.h> 00010 00011 bool Mover::move(const std::vector<int>& src, const std::vector<int>& dest, 00012 std::vector<int>& order, 00013 std::vector<int>& forbidden, 00014 int depth) { 00015 if (depth==0) { 00016 global_solved = false; 00017 solutions = 0; 00018 } 00019 if (global_solved) { 00020 if (depth>(int)global_best_order.size()) { 00021 return false; 00022 } 00023 } 00024 if (solutions>100) { 00025 return false; 00026 } 00027 00028 dbg_printf("* move in %d [%d] : %s / %s / %s\n", depth, 00029 solutions, 00030 vector2string(src).c_str(), 00031 vector2string(dest).c_str(), 00032 vector2string(order).c_str()); 00033 vector<int> best_order; 00034 if (src==dest) { 00035 return true; 00036 } 00037 bool solved = false; 00038 00039 for (size_t i=0; i<dest.size(); i++) { 00040 int x = dest[i]; 00041 if (std::find(forbidden.begin(),forbidden.end(),x)!=forbidden.end()) { 00042 continue; 00043 } 00044 vector<int>::const_iterator it = std::find(src.begin(), 00045 src.end(), 00046 x); 00047 bool moving = false; 00048 bool toStart = false; 00049 int x2 = -1; 00050 if (it==dest.begin()) { 00051 if (i!=0) { 00052 x2 = dest[i-1]; 00053 moving = true; 00054 } 00055 } else if (i==0) { 00056 moving = true; 00057 toStart = true; 00058 } else if (*(it-1)!=dest[i-1]) { 00059 x2 = dest[i-1]; 00060 moving = true; 00061 } 00062 if (!moving) continue; 00063 00064 vector<int> norder = order; 00065 vector<int> nforbidden = forbidden; 00066 vector<int> nsrc = src; 00067 nsrc.erase(nsrc.begin()+(it-src.begin())); 00068 if (toStart) { 00069 nsrc.insert(nsrc.begin(),x); 00070 } else { 00071 vector<int>::iterator it2 = std::find(nsrc.begin(), 00072 nsrc.end(), 00073 x2); 00074 nsrc.insert(it2+1,x); 00075 } 00076 /* 00077 if (src[i]==dest[i]) { 00078 continue; 00079 } 00080 nsrc.erase(nsrc.begin()+i); 00081 nsrc.insert(nsrc.begin()+(it-dest.begin()),x); 00082 */ 00083 norder.push_back(x); 00084 nforbidden.push_back(x); 00085 //if (x2!=-1) { 00086 //nforbidden.push_back(x2); 00087 //} 00088 bool ok = move(nsrc,dest,norder,nforbidden,depth+1); 00089 if (!ok) continue; 00090 if (norder.size()<best_order.size() || !solved) { 00091 best_order = norder; 00092 solved = true; 00093 solutions++; 00094 if (best_order.size()<global_best_order.size() || !global_solved) { 00095 global_best_order = norder; 00096 global_solved = true; 00097 } 00098 } 00099 } 00100 if (!solved) { 00101 return false; 00102 } 00103 order = global_best_order; 00104 dbg_printf("* move out %d : %s / %s / %s\n", depth, 00105 vector2string(src).c_str(), 00106 vector2string(dest).c_str(), 00107 vector2string(order).c_str()); 00108 return solved; 00109 }