Home > Blockchain >  How do I choose a random number from a list?
How do I choose a random number from a list?

Time:01-19

I am creating a number-guessing game where the player has to guess a randomly generated number but I don't know how to choose a random number.

I have a variable called truenumber which is equal to a list of numbers, what I want to do is make it randomly choose from the list and compare it to the user's input.

    int truenumber; 
    truenumber = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;

So how do I make it pick a random number from the list each time?

#include <iostream>
using namespace std;

int main() {
    
    string message = "Hello";
    cout << message << endl;
    cout << "Lets play a game" << endl;
    cout << "Try to guess the number!" << endl;
 
    int truenumber; 
    truenumber = 1, 2, 3, 4, 5, 6, 7, 8, 9, 10;
    int number;
    cin >> number;

    if (number = truenumber) {   
        cout << "You got it right!" << endl;
    }
    else if (number > truenumber) {
        cout  << "Too high" << endl;
        cin >> number;
    }
    else (number < truenumber) {
        cout << "Too low" << endl;
        cin >> number;
    }
    
} 

I wasn't expecting this to work since truenumber doesn't have an actual value and I was trying to find a solution online but only found really complex solutions that didn't match my ideas.

CodePudding user response:

You can:

  1. Check array or list size
  2. Use rand() method from standard library

You can do it like this value = rand() % listSize. This would give you a random number from 0 to listSize.

Hope this would help.

CodePudding user response:

To get a random number you can use rand() or std::rand()

You will also need to use srand() to seed the random number (get a new random number)

To get a random number in a range, you can use the module operator.

https://godbolt.org/z/hfMaxGYjr

  • Related