开发者

c++ recursion help

开发者 https://www.devze.com 2023-02-17 01:44 出处:网络
I am having trouble with recursion. Can anyone show me how to get this into code form? given vector <int> with values 1,2,3,4,5,..

I am having trouble with recursion. Can anyone show me how to get this into code form?

given vector <int> with values 1,2,3,4,5,..

i want to write a function that compares all of the value with each other. i dont care about 1 != 2 being equivalent to 2 != 1 for now.

i am so bad at recursion

and i promise that this is not homework

EDIT what i am trying to do is sort out events of a schedule. i have multiple events happening on the same day and i want to figure out all of the permutations of the schedule

2 nested for loops wont work since i am comparing multiple (>2) values

event 1 @ 0100-0230, or @ 0200-0330
event 2 @ 1200-1500, or @ 0800-1100
event 3 @ 1200-1300, or @ 1300-1400, or @ 1400-1500
.
.
.

for each comparion, i want开发者_StackOverflow to find out if that set of events intersect. i am not trying to find a set of events that all do not intersect

i want to get an output like

event 1 @ 0100-2300, event 2 @ 0800-1100, event 3 @ 1200-1300 // will be printed out
event 2 @ 0200-0330, event 2 @ 1200-1500, event 3 @ 1200-1300 // will be ignored


I guess you're investigating the relationship between recursion and iteration. Normally, simple iteration translates into tail recursion - the kind of recursion where recursive call is the last thing you do, so there is no need to have deep stack.

This is a bit of a pseudocode, plus it's not tested - but it should work.

void compareOne(int compareWith, iterator b, iterator e) {
    if (b == e) return;
    if (compareWith == *b) {
        // do something
    }
    compareOne(compareWith, b+1, e);
}


void compareAll(iterator b, iterator e) {
    if (b == e) return;
    compareOne(*b, b+1, e);
    compareAll(b+1, e);
}


I am betting this is homework... but I don't understand why you need recursion:

for(int i = 0; i<v.size(); ++i)
{
   for(int j = i+1; j < v.size(); ++j)
   {
      compare v[i] and v[j]
   }
}


Why do you need recursion? Simple iteration would do:

using namespace std;
vector<int> v;
...
for (int i = 0; i < v.size() - 1; i++)
    for (int j = i + 1; j < v.size(); j++)
        if (v[i] == v[j])
            cout << "Oops" << endl;

Or you can use iterators:

vector::const_iterator beforelast = v.end(); --beforelast;
for (vector::const_iterator i = v.begin(); i != beforelast; ++i)
    for (vector::const_iterator j = i + 1; j != v.end(); ++j)
        if (*i == *j)
            cout << "Oops" << endl;

One can try to solve the problem with a recursion:

bool f(vector<int>& v, int lastidx)
{
    int lastval = v[lastidx];
    for (int i = 0; i < lastidx; i++)
        if (v[i] == lastval)
            return false;
    return f(v, lastidx - 1);
}

However, the non-recursive solution is better in my opinion.

0

精彩评论

暂无评论...
验证码 换一张
取 消