Recursion of for's

此生再无相见时 提交于 2019-12-03 15:31:05

I did recursion to count possibility myself, but love you guys for all your help.

My recursion is

void col(int ilosc)
{
    static int st;
    for (int i = st++; i < k; i++)
    {
        if (ilosc > 1)
            col(ilosc - 1);
        else
            sposob++;
    }
}

where ilosc is digits number and sposob is count of possible positions numbers.

NOTE: sposob and k is global variables.

I am not sure whether recursion is the best choice here, but you could do it like this:

typedef std::vector<int> IV;
IV getFirst(int k){
    IV res;
    for (int i=0;i<k-1;i++){res.push_back(i+1);}
    return res;
}

bool getNext(IV& numbers,int i){
    if (i==-1){return false;} // end of recursion
    if (numbers[i]>i+1){return getNext(numbers,i-1);}
    numbers[i]++;
    return true;
}
bool getNext(IV& numbers){  // start of recursion
    return getNext(numbers,numbers.size()-1);
}

int main() {
    IV numbers = getFirst(5);
    for (int i=0;i<numbers.size();i++){std::cout << numbers[i];}
    std::cout << std::endl;
    while(getNext(numbers)){
        for (int i=0;i<numbers.size();i++){std::cout << numbers[i];}
        std::cout << std::endl;
    }
}

I think this will get you pretty close. I have an occasional repeat here, but this should set you on the right path.

const int max_depth = 5; // How long your string is
const int max_digit = 3; // Max digit you are counting to
int *nums = new int [max_depth];

void recurse_count(int depth)
{
    if (depth < max_depth)
    {
        for(int i = depth; i <= depth+1; i++)
        {
            nums[depth] = i;
            recurse_count(i+1);
        }
    }
    else
    {
        for (int j = 0; j < max_depth; j++)
            cout<<nums[j]+1;
        cout<<endl;
    }
}

int main()
{
    recurse_count(0);
    return 0;
}

My approach (still too early in the evening probably, I had problems with it)

namespace detail
{
    void recurse_hlp(int min, int max, std::vector<int> vals, std::function<void(const std::vector<int>&)> f, std::size_t ptr)
    {
        if (ptr == vals.size())
            f(vals);
        else
        {
            for (int i = min; i <= max; ++i)
            {
                vals[ptr] = i;
                recurse_hlp(min, max, vals, f, ptr + 1);
            }
        }
    }
}

void recurse(int min, int max, int count, std::function<void(const std::vector<int>&)> f)
{
    std::vector<int> vals(count);
    detail::recurse_hlp(min, max, vals, f, 0);
}

void print(const std::vector<int>& vals)
{
    for (int v : vals)
        std::cout << v << " ";
    std::cout << std::endl;
}

int main()
{
    recurse(0, 5, 3, &print);
}

recurse gets a function accepting std::vector<int>, which contains all numbers from min to max up to count places.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!