尺上蚂蚁问题c++源码Ants On Ruler.docx

  1. 1、本文档共4页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
尺上蚂蚁问题c源码AntsOnRuler

尺上蚂蚁问题 Ants On Ruler国外真实面试“回家作业”题,还是加分题。本人绝对原创,c++实现。/*4. Ants on a Ruler (Bonus)Description:N red and black ants are placed on a metre stick with some initial orientation. Every ant travels at thesame rate (1 cm/second), and will walk until they walk off an end of the ruler. However, if two ants of thesame color collide, both will reverse directions and continue walking.Given the starting location of each ant (distance from the left-most part of the ruler in centimeters),initial direction (L or R) of each ant, as well as the color of each ant (R or B), write a function thatdetermines the total distance traveled by all the ants along the ruler.Function prototype:float totalDistance(std::vectorint const locations,std::string orientation,std::string color)Example:totalDistance( {20}, L, B) = 20.0totalDistance( {20,80}, RL, RR) = 160.0*/const int L=100;//1mconst int SPEED=1;//1cm/secondstruct Ant{intiLocation;char cDirection;char cColor;intiDistance;boolbWalked;Ant(){iLocation = 0;cDirection = L;cColor = R;iDistance = 0;bWalked = false;}Ant(intiLoc, char cDir, char cClr){iLocation = iLoc;cDirection = cDir;cColor = cClr;iDistance = 0;bWalked = false;}Ant(const Ant a){iLocation = a.iLocation;cDirection = a.cDirection;cColor = a.cColor;iDistance = a.iDistance;bWalked = false;}~Ant(){};};float totalDistance(std::vectorint const locations,std::string orientation,std::string color){float iTotalDistance = 0;//initializestd::vectorAnt ants;for (inti=0;i(int)locations.size();i++){ants.push_back(Ant((int)locations[i],orientation[i],color[i]));}//remove out of range antsfor (std::vectorAnt::iterator it=ants.begin();it!=ants.end();){if (0=it-iLocation || L=it-iLocation){iTotalDistance += it-iDistance;it = ants.erase(it);}else++it;}boolbFirst = true;while(!ants.empty()){//1secondfor(std::vectorAnt::iteratoritSet=ants.begin(); itSet!=ants.end(); ++itSet){itSet-bWalked = false;}//every ant walks in 1 secondfor(inti=0;i(int)ants.size();i++){if (ants[i].bWalked) continue;boolbFoundCol

文档评论(0)

yan698698 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档