]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | //---------------------------------------------------------------------------// |
2 | // Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com> | |
3 | // | |
4 | // Distributed under the Boost Software License, Version 1.0 | |
5 | // See accompanying file LICENSE_1_0.txt or copy at | |
6 | // http://www.boost.org/LICENSE_1_0.txt | |
7 | // | |
8 | // See http://boostorg.github.com/compute for more information. | |
9 | //---------------------------------------------------------------------------// | |
10 | ||
11 | #ifndef BOOST_COMPUTE_ALGORITHM_RANDOM_SHUFFLE_HPP | |
12 | #define BOOST_COMPUTE_ALGORITHM_RANDOM_SHUFFLE_HPP | |
13 | ||
14 | #include <vector> | |
15 | #include <algorithm> | |
16 | ||
17 | #include <boost/range/algorithm_ext/iota.hpp> | |
18 | ||
19 | #include <boost/compute/system.hpp> | |
20 | #include <boost/compute/functional.hpp> | |
21 | #include <boost/compute/command_queue.hpp> | |
22 | #include <boost/compute/container/vector.hpp> | |
23 | #include <boost/compute/algorithm/scatter.hpp> | |
24 | #include <boost/compute/detail/iterator_range_size.hpp> | |
25 | ||
26 | namespace boost { | |
27 | namespace compute { | |
28 | ||
29 | /// Randomly shuffles the elements in the range [\p first, \p last). | |
30 | /// | |
31 | /// \see scatter() | |
32 | template<class Iterator> | |
33 | inline void random_shuffle(Iterator first, | |
34 | Iterator last, | |
35 | command_queue &queue = system::default_queue()) | |
36 | { | |
37 | typedef typename std::iterator_traits<Iterator>::value_type value_type; | |
38 | ||
39 | size_t count = detail::iterator_range_size(first, last); | |
40 | if(count == 0){ | |
41 | return; | |
42 | } | |
43 | ||
44 | // generate shuffled indices on the host | |
45 | std::vector<cl_uint> random_indices(count); | |
46 | boost::iota(random_indices, 0); | |
47 | std::random_shuffle(random_indices.begin(), random_indices.end()); | |
48 | ||
49 | // copy random indices to the device | |
50 | const context &context = queue.get_context(); | |
51 | vector<cl_uint> indices(count, context); | |
52 | ::boost::compute::copy(random_indices.begin(), | |
53 | random_indices.end(), | |
54 | indices.begin(), | |
55 | queue); | |
56 | ||
57 | // make a copy of the values on the device | |
58 | vector<value_type> tmp(count, context); | |
59 | ::boost::compute::copy(first, | |
60 | last, | |
61 | tmp.begin(), | |
62 | queue); | |
63 | ||
64 | // write values to their new locations | |
65 | ::boost::compute::scatter(tmp.begin(), | |
66 | tmp.end(), | |
67 | indices.begin(), | |
68 | first, | |
69 | queue); | |
70 | } | |
71 | ||
72 | } // end compute namespace | |
73 | } // end boost namespace | |
74 | ||
75 | #endif // BOOST_COMPUTE_ALGORITHM_RANDOM_SHUFFLE_HPP |