This is the background:
Three million men with distinct names were laid end-to-end, reaching from New York to California. Each participant was given a slip of paper on which he wrote down his own name and the name of the person immediately west of him in the line. The man at the extreme western end of the line didn't understand what to do, so he threw his paper away; the remaining 2,999,999 slips of paper were put in a huge basket and taken to the National Archives in Washington, D.C. Here the contents of the basket were shuffled completely and transferred to magnetic tapes.
I'm doing the naive solution provide by tutor, which random find a Xc
, then use it search in the unordered_map, if it have this Xc
as key, get the value of that key, which is the west name for nameMap1(shows below)
, or east name for nameMap2
search until can't find the westerly name or easterly name.
According to this, I have following code.
unique_ptr<string> temXc;
nameList1.push_back(*westName);
temXc.reset(new string);
temXc = move(westName);
bool isRunning = true;
while (isRunning==true)
{
unordered_map<string, string>::const_iterator gotWest = nameMap1.find(*temXc);
if (gotWest == nameMap1.end())
{
nameMap1.clear();
isRunning = false;
}
else
{
temWN.reset(new string);
*temWN = gotWest->second;
nameList1.push_back(*temWN);
nameMap1.erase(*temXc);
temXc.reset(new string);
temXc = move(temWN);
}
}
The while loop should help me to find the most westerly name, but it didn't.
For example as the background said, the name should shows like this:
- e,f
- a,b
- b,c
- c,d
- d,e
the first name should be the east name, another is west name.
If I randomly choose b
as Xc
, this while loop can give the list which is b, c, d, e, f
which works fine, but if I change to 3M.txt
which have 3M names, it's not working, the answer do give me a list, but after I check the 3M.txt
file, I find out the last name still have a westerly neighbour, and is the first name of the list(which is Xc
).