Home > Blockchain >  Players Matching Algorithm
Players Matching Algorithm

Time:01-09

Example when player register tournament push vector and when start game matching players and add the list (list have struct and 2 players insert 1 list) and erase in vector. Winner player add repeat vector. When round is finish (example vector have 101 players, matching 100 players fight and winner is insert again attenders vector 101th player is pass by and move next round). I'm i'm struggling for matching, i'm coding but when move next round enters an infinite loop. What is my mistakes? (sorry for bad English) My codes;

struct sFighters
{
    sFighters(int p1, int p2) : p1(p1), p2(p2) {}
    int p1;
    int p2;
};

std::vector<int> vec;
std::list<sFighters> dList;

void AddVec(int id)
{
    if (const auto& it = std::find(vec.begin(), vec.end(), id); it == vec.end())
        vec.push_back(id)
    else
        std::cout << "Already in vec" << std::endl;
}

void MakeList()
{
    for (auto i = vec.size() - 1; i > 0; i-=2 )
    {
        dList.push_back(sFighters(vec[i], vec[i-1]));
        std::erase(vec, vec[i]); std::erase(vec, vec[i-1]); // c  20 features
    }
    StartFightMode(); // for start fight player1 and player2
}

void FinishFight(int win, int lose)
{
    if (const auto& it = std::find_if(dList.begin(), dList.end(),
    [win,lose] (const auto& st)
    {return (st->GetID() == p1 || st->GetID() == p2); }
    ); it != dList.end())
    {
        dList.erase(it);
    }
    vec.push_back(win);

    if (dList.empty() && vec_size > 1)
    {
        MakeList();
        return;
    }

    if (dList.empty() && vec.size() == 1)
    {
        std::cout << "Winner player id: " << vec.begin() << std::endl; 
        return;
    }

    
    StartFightMode(); // check dList and start fight player1 and player2
}

CodePudding user response:

My c is a little rusty, but in MakeList if i is unsigned and you're subtracting two from it in each iteration of the loop it might never be less than or equal to zero.

CodePudding user response:

in the loop for (auto i = vec.size() - 1; i > 0; i will be unsigned long long. So vec.size() is even i will be odd. When i==1 and you call i-=2 i will become 2^64-1>0 so the loop will continue.

Solution1: instead of auto write int as the type of i (you will have a small loss in speed but should be neglegable)

Solution2: Go from the beggining and iterate forwards.

Impertant note: std::erase will delete all elements which are equal to vec[i] or vec[i-1]. If you have an other element equal to one of them the size of vec will decrease by more than 2 so in the next loop you will index out from vec. Use pop_back() instead (much faster too)

  •  Tags:  
  • Related