// transgraph problem, using Thrust

#include <stdio.h>

#include <thrust/device_vector.h>
#include <thrust/transform.h>
#include <thrust/remove.h>
#include <thrust/sequence.h>

// forms one row of the output matrix
struct makerow {
   const thrust::device_vector<int>::iterator outmat;  
   const int nc;  // number of columns
   makerow(thrust::device_vector<int>::iterator _outmat,int _nc) : 
      outmat(_outmat), nc(_nc) {}
   __device__
   // the j-th 1 is in position i of the orig matrix
   bool operator()(const int i, const int j)  
   {  outmat[2*j] = i / nc;
      outmat[2*j+1] = i % nc;
   }
};

int main(int argc, char **argv)
{  int x[12] = {
      0,1,1,0,
      1,0,0,1,
      1,1,0,0};
   int nr=3,nc=4,nrc = nr*nc,i;
   thrust::device_vector<int> hx(x,x+nrc);
   thrust::device_vector<int> ones(x,x+nrc);
   thrust::counting_iterator<int> seqb(0);
   thrust::counting_iterator<int> seqe = seqb + nrc;
   // get 1-D indices of the 1s
   thrust::device_vector<int>::iterator newend =
      thrust::copy_if(seqb,seqe,hx.begin(),ones.begin(),
         thrust::identity<int>());
   int n1s = newend - ones.begin();
   thrust::device_vector<int> newmat(2*n1s);
   thrust::device_vector<int> out(n1s);
   thrust::counting_iterator<int> seq2b(0);
   // thrust::counting_iterator<int> seq2e = seq2b + nrc;
   thrust::transform(ones.begin(),newend,seq2b,out.begin(),
      makerow(newmat.begin(),nc));
   for (i = 0; i < n1s; i++) 
      printf("%d %d\n",newmat[2*i],newmat[2*i+1]);
}
