Unique random numbers in an array
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2

Thread: Unique random numbers in an array

Hybrid View

  1. #1
    Join Date
    Jan 2013
    Location
    Gastonia, NC
    Posts
    11

    Unique random numbers in an array

    Below is my code for a program that is suppose to generate and display six unique random numbers (between 1 and 54). The issue seems to be in my check for duplicates. I know what I am doing wrong but can't seem to find a way to fix it. I think it is getting stuck in an endless loop because the way I have written it looks like it checks the first value against itself which will of course look like a duplicate everytime. I am relatively new to programming, but catch on quickly....just a point in the right direction would be of immense help. Thanks.

    Code:
    #include<iostream>
    #include<ctime>
    using namespace std;
    
    //function prototype
    int getRandNumb();
    
    int main ()
    {
       srand((unsigned)time(NULL));
    
       //declare array
       int randomNum[6];
    
       //declare variable
       int checkNum = 0;
    	
       for (int x = 0; x < 6; x += 1)
       {
    	   randomNum[x] = getRandNumb();
    
    	   if (randomNum[x] == randomNum[0] || randomNum[1] || randomNum[2] || randomNum[3] ||randomNum[4] || randomNum[5])
    		   x -= 1;
    	   else
    		   cout << randomNum[x] << endl;
       } //end for
       
       cin.get();
       return 0;
    } //end of main function
    
    //*****function definition(s)*****
    int getRandNumb()
    {
        return rand()%54 - 1 + 1;
    } //end of getRandNumb function

  2. #2
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Posts
    12,098

    Re: Unique random numbers in an array

    Code:
    	   if (randomNum[x] == randomNum[0] || randomNum[1] || randomNum[2] || randomNum[3] ||randomNum[4] || randomNum[5])
    That's not how you write multiple conditions in C++. randomNum[1] is an expression by itself, so unless it's 0, the entire statement will always be true. The way you wrote the first check is the way you need to write them all.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  


Windows Mobile Development Center


Click Here to Expand Forum to Full Width

This is a CodeGuru survey question.


Featured


HTML5 Development Center