mardi 5 avril 2022

random number generater that doesnt repeat it self (cpp/c++)

I want to make a function that generates numbers but doesnt repeat it self. if every number is generated the array can be emptyed and it can start over again.

This is the code i made but it doesnt work the comments in the code explains the code a little the largest number that is alowed is "howManyWords" this is used to display words wich are stored in a array

i want to use it like this: array[random()]

#include <stdio.h>
#include <iostream>
#include <string>
#include <stdlib.h>

using namespace std;
//public scope
int howManyWords; // how many words you have enter

int random(){
    int random;
    int numbers[howManyWords];
    srand(time(0)); //changing the algoritm
    random = rand() % howManyWords;
    numbers[random] = random; // store the digit in the position in the array equal to the digit that is genenrated
    for(int i=0; i<howManyWords; i++){ // going through every ellement in the array
        if(numbers[i] == random){ // if the number is already generated, generate a differnt numbber
        random = rand() % howManyWords;
        }
    }
    return random;
}



Aucun commentaire:

Enregistrer un commentaire