lundi 25 mai 2020

First repeated number in an array C++

I need to find the first repeated number in an array without writing for, while or any loop. There is a given library where I have to use the Linear search and Array Enumerator classes. I tried to inherit from these classes but I couldn't figure it out how to connect the 2 linear search.

I want to solve this problem but using only the library without writing loops

vector<int> k = {8,1,4,9,9,1}
for (int i = 0; i < k.size() - 1; i++) {
 for (int p = i + 1; p < k.size(); p++) {
    if (k[i] == k[p]) {
        cout << k[i] << endl;
           i=k.size();
           p=k.size();
    }
  }
}

You can give this array to an enumerator

vector<int> k = {8,1,4,9,9,1};
ArrayEnumerator<int> enor(&k);

Then you can inherit from the LinSearch class, where you can override the cond(condition) function. This returns the first value which is greater than 5.

class MainCycle:public LinSearch<int>
{

public:
    MainCycle() {}
protected:
    bool cond(const int &e) const override
    {

        return e>5;
    }
};

Then you can give an object to that enumerator and run it.

MainCycle maincycle;
maincycle.addEnumerator(&enor);
maincycle.run();
maincycle.elem(); // the answer (return an int in this case)

Obviusly you can also inherit from the ArrayEnumerator class and override the functions(from where should the loop run, where should it end..)

template <typename Item>
class MyEnum: public ArrayEnumerator<Item>
{

public :

    MyEnum(const std::vector<Item> *v):ArrayEnumerator<Item>(v) {}
    void first() override
    {
        ArrayEnumerator<Item>::_ind = 1;
    }

    bool end()     const override
    {
        return ArrayEnumerator<Item>::_ind<=0;
    }

};

the library

Aucun commentaire:

Enregistrer un commentaire