Random Choosing

Feb 14, 2017 at 5:59pm
Hello!!!!!
I am new to C++ and to programing in general, I would really appreciate it if you guys can help me with creating a tiny simple program:

I want to be able to create a program that would randomly chose 10 of a certain number of given variables. For example, I would give the program 50 words, and it will choose a random 10 of them.

I am really excited to learn more about programing :)
Thanks in advance!!!!!
Feb 14, 2017 at 6:27pm
I would start working on it. See what you can do on your own. When you get stuck or have a specific question, ask it. I'm guessing you know at least some of the basics to get started. When you get to the random part here is a link that'll help you set it up.
http://www.cplusplus.com/reference/cstdlib/rand/
Feb 14, 2017 at 6:59pm
This isnt obvious to a new programmer, so I will give you a few more hints.
You can allocate the items you want to choose from and randomly select from those. This can be done using the built in vector container class with a built in algorithm (random shuffle) or by forcing a random value into the range of indices for an array.

the array is the easy and probably best to learn from if new to programming.

Feb 15, 2017 at 8:49am
Thank you very much, I'll start with the program and ask you if I encounter a problem,
The link is very helpful :) but i didnt find the vector container class

Thanks again
Feb 15, 2017 at 12:30pm
#include <vector>

it is a template container, so it looks like

vector v<int>; //a vector of integers. You can put anything in here, including your own types/classes.

Feb 15, 2017 at 2:11pm
but i didnt find the vector container class


for a rough and ready intro to std::vector : https://www.tutorialspoint.com/cplusplus/cpp_stl_tutorial.htm
for more detailed, technical introductions to std::vector:
http://www.cplusplus.com/reference/vector/vector/
http://en.cppreference.com/w/cpp/container/vector

for generating the 10 random numbers:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <random>
#include <vector>
#include <chrono>

int main()
{
    std::default_random_engine numGenerator(static_cast<unsigned int>(time(NULL)));

    std::uniform_int_distribution<int> range(0, 49);//index range of vector of 50 strings

    std::vector<int> randomNumbers{};

    for (std::size_t i = 0; i < 10; ++i)
    {
        randomNumbers.push_back(range(numGenerator));
    }
    for (const auto& elem : randomNumbers)
    {
        std::cout << elem << " ";
    }
}
Topic archived. No new replies allowed.