Search code examples
cudacopysequencethrust

thrust::sequence - how to increase the step after each N elements


I am using

thrust::sequence(myvector.begin(), myvector.end(), 0, 1)

and achieve good ordered list like:

0, 1, 2, 3, 4

My question is how can I achieve such a list below (the best way?)

0, 0, 0, 1, 1, 1, 2, 2 ,2, 3, 3, 3

I know how to make it with functors, so please do not try to answer it with functor. I want to learn if there is an optimized way for it in Thrust, or am I missing a simple way..


Solution

  • Something like this:

    thrust::device_vector<int> myvector(N);
    
    thrust::transform( thrust::make_counting_iterator(0),
                       thrust::make_counting_iterator(N),
                       thrust::make_constant_iterator(3),
                       myvector.begin(),
                       thrust::divides<int>() );
    

    (disclaimer, written in browser, never compiled or tested, use at own risk)

    should give you the sequence you are looking for by computing [0..N]//3 and outputting the result on myvector.


    Seeing as you are having trouble compiling your version, here is a complete example which compiles and runs:

    #include <thrust/device_vector.h>
    #include <thrust/transform.h>
    #include <thrust/functional.h>
    #include <thrust/iterator/counting_iterator.h>
    #include <thrust/iterator/constant_iterator.h>
    #include <cstdio>
    
    int main(void)
    {
        const int N = 18, M = 3;
        thrust::device_vector<int> myvector(N);
    
        thrust::transform(  thrust::make_counting_iterator(0),
                            thrust::make_counting_iterator(N),
                            thrust::make_constant_iterator(M),
                            myvector.begin(),
                            thrust::divides<int>() );
    
        for(int i=0; i<N; i++) {
            int val = myvector[i];
            printf("%d %d\n", i, val);
        }
        return 0;
    }