Random number generation in array

A

Artyom

Hi everybody!
Here's the problem:
I have an array of 4 integer elements and they must be initialized by random
numbers from 0 to 9 that shouldn't repeat. I tried many things, but some
elements (for example, first and third ones) continue repeating. Can you
propose an algorithm that solves this?
Thank you!
 
L

lilburne

Artyom said:
Hi everybody!
Here's the problem:
I have an array of 4 integer elements and they must be initialized by random
numbers from 0 to 9 that shouldn't repeat. I tried many things, but some
elements (for example, first and third ones) continue repeating. Can you
propose an algorithm that solves this?
Thank you!

std::set<int> numbers;
while (numbers.size() <= 4) {
int random_int = get_random_integer();
numbers.insert(random_int);
}

// move values from set into array
 
J

John Harrison

Artyom said:
Hi everybody!
Here's the problem:
I have an array of 4 integer elements and they must be initialized by random
numbers from 0 to 9 that shouldn't repeat. I tried many things, but some
elements (for example, first and third ones) continue repeating. Can you
propose an algorithm that solves this?
Thank you!

Fill an array (size 10) with numbers 0 to 9

Go though array randomly swapping each element with a later element (a
random shuffle)

Pick first four elements from randomly shuffled array.

john
 
D

David Harmon

Sorry, it doesnt. ;)

What's not to like about it?

int nums[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::random_shuffle(nums, nums+10);
std::copy(nums, nums+4, std::eek:stream_iterator<int>(std::cout, " "));
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top