算法练习2:Two fighters, one winner.

来源:互联网 发布:mac safari缓存文件 编辑:程序博客网 时间:2024/06/05 12:41

算法练习随笔2

  • 题目:

    Create a function that returns the name of the winner in a fight between two fighters.
    Each fighter takes turns attacking the other and whoever kills the other first is victorious. Death is defined as havinghealth <= 0.
    Each fighter will be a Fighter object/instance. See the Fighter class below in your chosen language.
    Both health and damagePerAttack (damage_per_attack for python) will be integers larger than0. You can mutate theFighter objects.

  • public和private:

    在public: 下的成员,是类的公有成员,别的类或者主函数可以申明个对象直接访问,而private: 下的是私有成员,只有类的内部能访问,类的外部无法访问的.

  • 析构函数和构造函数:

class MyClass{public:    MyClass()//构造函数    {        cout << "Constructors" << endl;    }    ~MyClass()//析构函数    {        cout << "Destructors" << endl;    }    };

new的时候,其实做了三件事,一是:调用::operator new分配所需内存。二是:调用构造函数。三是:返回指向新分配并构造的对象的指针。
delete的时候,做了两件事,一是:调用析构函数,二是:调用::operator delete释放内存。

  • this指针的运用:
    下示的代码中的this指的是class里面的成员,
this->name = name;
    的意思是将构造函数里面的"name"赋值给private里面的"name"
class Fighter{private:    std::string name;    int health;    int damagePerAttack;public:    Fighter(std::string name, int health, int damagePerAttack)    {        this->name = name;        this->health = health;        this->damagePerAttack = damagePerAttack;    }
  • 交换函数swap:
    交换两个数的值.
 std::swap(attacker, defender)
  • 构造函数和private的关系:
    因为private的成员类间不能访问,所以需要用到构造函数来赋初始值.

  • 最后的代码:

std::string declareWinner(Fighter* fighter1, Fighter* fighter2, std::string firstAttacker){    int health1, health2,flag;    health1 = fighter1->getHealth();    health2 = fighter2->getHealth();    if (firstAttacker == fighter1->getName())    {        health2-=fighter1->getDamagePerAttack();        //cout << "health2="<<health2 << endl;        flag = 0;    }    else    {        health1 -= fighter2->getDamagePerAttack();        //cout << "health1=" << health1 << endl;        flag = 1;    }    while (1)    {        if (health1 <= 0)        {            return fighter2->getName();        }        else        {            if (health2 <= 0) return fighter1->getName();        }        if (flag == 0)        {            health1 -= fighter2->getDamagePerAttack();            //cout << "health1=" << health1 << endl;            flag = 1;        }        else        {            health2 -= fighter1->getDamagePerAttack();            //cout << "health2=" << health2 << endl;            flag = 0;        }    }}
  • 比较大神代码:
std::string declareWinner(Fighter* fighter1, Fighter* fighter2, std::string firstAttacker){ // Number of blows each fighter can survive: int n1 = (fighter1->getHealth() - 1) / fighter2->getDamagePerAttack(); int n2 = (fighter2->getHealth() - 1) / fighter1->getDamagePerAttack(); return n1 > n2 ? fighter1->getName()      : n1 < n2 ? fighter2->getName()      :           firstAttacker;}
0 0
原创粉丝点击