dimanche 31 mai 2020

Randomizer picks a number from the vector and delete it

So, program picks this number from the vector, it's actually a sequence {1...n} and I want to print out and delete random number from it. However, everytime program prints out {n...1} sequence. Example: Vector(1,2,3,4,5) => program picks random number 4 => Vector(1,2,3,5) => random number 1 => Vector(2,3,5) and until Vector(). So, program will print (4,1,...). In case of this program, it always prints out (5,4,3,2,1) for Vector(1,2,3,4,5).

int main()
{
    srand(time(NULL));
    rand();
    int toReturn;
    std::cout << "Enter the number of tickets: ";
    std::cin >> toReturn;
    std::cout << std::endl;
    std::vector<int> nums;


    for (int i = 1; i <= toReturn; ++i)
    {
        nums.push_back(i);
    }

    int choice=0;
    bool checked=0;
    while (nums.size() > 0)
    {
        bool inVector=0;
        choice = rand() % toReturn + 1;

        while(inVector == 0)
        {
            choice = rand() % toReturn + 1;

            for (int i = 0; i < nums.size(); ++i)
            {
                if (choice == nums[i])
                {
                    inVector = 1;
                }
                else
                {
                     inVector = 0;
                }
            }
        }
        std::cout << "Why not check the ticket " << choice << std::endl;
        std::cout << "Did u do it right?" << std::endl;
        std::cin >> checked;
        if (checked)
        {
            nums.erase(std::remove(nums.begin(), nums.end(), choice), nums.end());
        } 

        else
        {
             continue;
        }
    }
    if (nums.size() == 0)
    {
        std::cout << "You checked all tickets!!!";
    }
    return 0;
}

I would be glad if you leave any suggestion to code refactoring




Aucun commentaire:

Enregistrer un commentaire