Skip to content
Snippets Groups Projects

HW7

Merged Sourish Kundu requested to merge dev-hw7 into main
Files
5
HW07/count.cu 0 → 100644
+ 31
0
#include <thrust/sort.h>
#include <thrust/inner_product.h>
#include <thrust/unique.h>
#include "count.cuh"
void count(const thrust::device_vector<int> &d_in,
thrust::device_vector<int> &values,
thrust::device_vector<int> &counts)
{
// Creating temp vector and sorting it
thrust::device_vector<int> d_temp = d_in;
thrust::sort(d_temp.begin(), d_temp.end());
// Calculating the number of unique elements
// For the first vector of the inner product, we're using just the temp vector. For the second vector, we're using the temp vector shifted by one element to the right.
// The result of the inner product is a vector of 1s and 0s, where 1 means that the two elements are different and 0 means that they are the same.
// The sum of this vector is the number of unique elements (minus 1, which is why we need to add 1 at the end).
// Note: the keys are sorted, which is why we can use the shifted vector.
int num_of_unique_nums = thrust::inner_product(d_temp.begin()+1, d_temp.end(), d_temp.begin(), 0, thrust::plus<int>(), thrust::not_equal_to<int>()) + 1;
// Resizing the values and counts vectors to the number of unique elements
values.resize(num_of_unique_nums);
counts.resize(num_of_unique_nums);
// The keys are the original elements, and the values are 1s.
// Reducing by key will sum the values for each key, which in this case results in the number of times that specific element appears.
// Note: the keys are sorted, which is why we can use reduce_by_key.
thrust::reduce_by_key(d_temp.begin(), d_temp.end(),
thrust::make_constant_iterator(1),
values.begin(), counts.begin());
}
\ No newline at end of file
Loading