Skip to content
MPGHThe Dark Arts
/
RegisterLog in
Forum
Community
What's NewLatest posts across the boardTrendingHottest threads right nowSubscribedThreads you follow
Discussion
GeneralIntroductionsEntertainmentDebate FortFlaming & Rage
Board
News & AnnouncementsMPGH TimesSuggestions & HelpGiveaways
More Sections
Art & Graphic DesignProgrammingHackingCryptocurrency
Hacks & Cheats
Games
ValorantCS2 / CS:GOCall of Duty / WarzoneFortniteApex LegendsEscape From Tarkov
+14 moreLeague of LegendsGTA VMinecraftRustROTMGBattlefieldTroveBattleOnCombat ArmsCrossFireBlackshotRuneScapeDayZDead by Daylight
Resources
Game Hacking TutorialsReverse EngineeringGeneral Game HackingAnti-CheatConsole Game Hacking
Tools
Game Hacking ToolsTrainers & CheatsHack/Release NewsNew
Submit a release →Share your cheat, tool, or config with the community.
AINEW
AI Tools
General & DiscussionPrompt EngineeringLLM JailbreaksHotAI Agents & AutomationLocal / Open Models
AI × Gaming
AI Aimbots & VisionML Anti-CheatGame Bots & Automation
Create
AI Coding / Vibe CodingAI Art & MediaAI Voice & TTS
The AI frontier →Where game hacking meets modern machine learning. Jump in.
Marketplace
Buy & Sell
SellingBuyingTradingUser Services
Trust & Safety
Middleman LoungeMarketplace TalkVouch Copy Profiles
Money
Cryptocurrency TalkCurrency ExchangeWork & Job Offers
Start selling →List accounts, services, and goods. Use the middleman to trade safe.
MPGH The Dark Arts

A community for offensive security research, reverse engineering, and AI.

Community

ForumMarketplaceSearch

Account

RegisterLog in

Legal

Privacy PolicyForum RulesHelp & FAQ
© 2026 MPGH · All rights reserved.Built by the community, for the community. For educational purposes onlyContent is shared for security research and education — we don't condone illegal use. You're responsible for complying with applicable laws. Use at your own risk.
Home › Forum › Programming › C++/C Programming › Generating Unique Random Numbers?

Generating Unique Random Numbers?

Posts 1–11 of 11 · Page 1 of 1
AP
apandhi
Generating Unique Random Numbers?
Okay guys, here is a problem I'm having. I have an array and I want to generate 10 random integers that dont overlap between 1 and 25. This is what I have but it keeps overlapping. Any Ideas?
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>

using namespace std;

int main(){
	int question[9];
	unsigned seed = time(NULL);
	srand(seed);
	for(int i=0; i < 10; i++){
		question[i]=0;
	}
	for(int i=0; i < 10; i++){
		question[i] = rand()/100%(10)+ 1;
			//rand();
		for(int x=0; x < 10; x++){
			if(i==x) continue;
			else{
				while(question[i]==question[x]){
					question[i] = rand()/100%(10)+ 1;
				}
			}
		}
		cout << question[i] << endl;
	}
	getch();
}
#1 · 16y ago
Void
Void
What do you mean it's overlapping? Meaning all the integers stored in the arrays have to be different from each other?
#2 · 16y ago
AP
apandhi
Quote Originally Posted by Void View Post
What do you mean it's overlapping? Meaning all the integers stored in the arrays have to be different from each other?
Yea, for example there cant be two 7s
#3 · 16y ago
why06
why06
U need to create an array of every unique number u generate. WHen u generate a new number compare it to all the entries in that array. if it comes up that none of them are a match add that number to the array. if not recalculate a rand # untill you get a unique one
Code:
int numbersfound = 1;
//generate 1st number
int numbers[10];
numbers[0] = gen_num ;
while(numbersfound < 10)
{
//generate number here
for(int i = 0; i < numbersfound; i++)
{
if(generated_number == numbers[i])break;
if(i == numbersfound-1)numbersfound++;
}
}
#4 · 16y ago
AP
apandhi
Quote Originally Posted by why06 View Post
U need to create an array of every unique number u generate. WHen u generate a new number compare it to all the entries in that array. if it comes up that none of them are a match add that number to the array. if not recalculate a rand # untill you get a unique one
Code:
int numbersfound = 1;
//generate 1st number
int numbers[10];
numbers[0] = gen_num ;
while(numbersfound < 10)
{
//generate number here
for(int i = 0; i < numbersfound; i++)
{
if(generated_number == numbers[i])break;
if(i == numbersfound-1)numbersfound++;
}
}
Im sorry but what do I put here:
"numbers[0] = gen_num ;"?
#5 · 16y ago
Void
Void
Sorry for the wait, it's late and I'm tired..

[php]
#include <iostream>
#include <ctime>

using namespace std;

int question[10];

int main()
{
srand(time(NULL));

while(true)
{
gen:
//generate
for(int i=0;i<9;i++)
{
question[i] = rand()%25;
}
//generate

for(int i=0;i<9;i++)
{
for(int n=0;n<9;n++)
{
if(i != n)
{
if(question[i] == question[n])
{
goto gen;
}
}
}
}
break;
}


for(int i=0;i<9;i++)
{
cout << question[i] << endl;
}

cin.get();
}
[/php]

It keeps generating until it gets a set with all different numbers. Not sure if this is what you're looking for..

Sorry if you hate "goto"s, I couldn't think of any other clean way of breaking out of a crap load of loops in a single line.
#6 · 16y ago
r_arraz
r_arraz
[LEECHED]
I got some code here I found that works, courtesy of bling bling vr6 for their source code involving generating random numbers with validation for unique numbers, and Infarction for cleaning up his code so that it would work properly . I mainly just inserted the LinearSearch function and replaced one of your for loops with the for loop Infarction fixed. Just google "c++ unique random numbers" and I got it from the first result. Anyway here it is .

Code:
#include <iostream>
#include <ctime>
#include <conio.h>

using namespace std;

int LinearSearch(const int number[], int value) //Determines if the given number already exists
{
    int index = 0;
    int position = -1; 
    bool found = false; //Bool for duplicate number

    while (index < 15 && !found)
    {
        if (number[index] == value) //If any integer in the list is equal to the new
        {                           //random number
            found = true; //Sets bool to true because it found a duplicate
            position = index; //Sets position to where it found the duplicate
        }
        index++; //Increments through the list of numbers
    }
    return position; //Returns -1 if number is unique, else if duplicate is found
}



int main(){
    int question[14]; //List of numbers
    int temp; //Random number holder
    unsigned seed = time(NULL);
    srand(seed);

    for(int i=0; i < 15; i++){
        question[i]=0; //Set all integers in array to 0
    }

      for(int i = 0; i < 15; i++)
      {
      do {
      temp = rand() % 15 + 1; // Generate random number
      } 
      while (LinearSearch(question, temp) != -1); // Call function to check for duplicates of randomly generated number
                                                  //Repeats proccess until return value is equal to -1
      question[i] = temp; // If it's unique then save the number
      cout << question[i] << endl; //Print to screen
      }
    getch(); //Wait for user to press any key
    }
Please tell me if it's not ok to leech this.
#7 · edited 16y ago · 16y ago
SC
schim
Like r_arraz said, using the rand();
Function will get you an array of (pseudo) random numbers
Here is an very easy tut on how to do it, and some theory as well(youtube):

[YOUTUBE]PZZUJ1fxG04[/YOUTUBE]
#8 · 16y ago
Hell_Demon
Hell_Demon
Code:
class UniqueRand
{
private:
    int min, max, OptionsLeft;
    bool bUsed[];

public:
    void Initialize(int min=0, int max=1000)
    {
        this.min = min;
        this.max = max;
        bUsed = new bool[max-min];
    }
    int Random()
    {
        for(int i=0; i<max-min; i++)
        {
            if(bUsed[i]==false)
            {
                 OptionsLeft++;
            }
        }
        if(OptionsLeft==0)
        {
             return -1;
        }
        int retval = (rand()%(max-min));
        while(bUsed[retval]==true)
        {
            retval = (rand()%(max-min));
        }
        bUsed[retval]=true;
        OptionsLeft=0;
        return (retval+min);
    }
    void Reset()
    {
        for(int i=0; i<max-min; i++)
        {
            bUsed[i]=false;
        }
    }
};
usage:
Code:
UniqueRand myRandGen;
myRandGen.Initialize(20,500);
int mygeneratedrang = myRandGen.Random();
note: written in here, so untested meaning it will probably throw some errors at you =P
#9 · edited 16y ago · 16y ago
Mr.Magicman
Mr.Magicman
i would say you use rand_s ( ) instead its much better
#10 · 16y ago
Hell_Demon
Hell_Demon
Quote Originally Posted by iopop9 View Post
i would say you use rand_s ( ) instead its much better
the safe functions are bullshit =P
#11 · 16y ago
Posts 1–11 of 11 · Page 1 of 1

Post a Reply

Similar Threads

  • Random Number GeneratorBy Iam"iDude" in Visual Basic Programming
    5Last post 18y ago
  • [TuT]Generate Random NumberBy Iamazn1 in Visual Basic Programming
    1Last post 16y ago
  • [Question]Random Number+Letter GeneratorBy Dreamer in Visual Basic Programming
    4Last post 16y ago
  • [Question] Random number below a set numberBy That0n3Guy in C++/C Programming
    4Last post 16y ago
  • Fill with random numbers between 0-12By ppl2pass in Visual Basic Programming
    13Last post 16y ago

Tags for this Thread

None