Yes, swapping would work much better, thank you!
Here what I have now, I am essentially implementing a partial random
shuffle:
[I guess if I wanted to get crazy I could create a custom int type that
would construct itself into a sequence during resize operation...hmmm]
void RandomIndices(
int in_count,
int in_range,
IntVector & out_index_list)
{
assert( in_count <= in_range );
out_index_list.resize(in_range);
IntVector::iterator p = out_index_list.begin();
IntVector::iterator end = out_index_list.end();
std::generate(p, end, SequenceGenerator());
--in_range;
if( in_range )
{
for(int i=0; i<in_count; ++i)
{
int n( RandomNumber(in_range) );
std::swap(*p,*(p + n));
--in_range;
++p;
}
out_index_list.resize(in_count);
}
}
Adam Fineman wrote:
Ross MacGregor wrote:
I have a very simple yet complicated problem. I want to generate a
random list of indices (int's) for a container.
How about this?
--------------
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>
using namespace std;
int
main()
{
vector<int> v;
// fill the vector with whatever
copy(istream_iterator<int>(cin), istream_iterator<int>(),
back_inserter(v));
typedef vector<int>::const_iterator Iter;
vector<Iter> it;
for (Iter i = v.begin(); i != v.end(); ++i)
it.push_back(i);
// output three random values from v
random_shuffle(it.begin(), it.end());
for (vector<Iter>::size_type i = 0; i < 3; ++i)
cout << *it[i] << ' ';
cout << '\n';
return 0;
}
----------------
- Adam