Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |
 User Name: Password: Remember me

New Free Tools on Dev Shed!
We're Excited to announce that Dev Shed now has 70 free tools on the site. To learn more, click here!

 Dev Shed Forums Sponsor:
#1
November 29th, 2006, 11:53 AM
 Omega_1405
Registered User

Join Date: Nov 2006
Posts: 7
Time spent in forums: 1 h 41 m 45 sec
Reputation Power: 0
Generating multiple nonrepeating random numbers

For a project, I'm supposed to write a program which simulates a dog race. There are 8 dogs in the race, and I need it to come up with who comes in first, second, and third. I know how to make random numbers, but I don't know how to get three different random numbers. Here's what I have so far.

PHP Code:
``` #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) {   int dog=0, place=0, chips=3, num1=0, num2=0, num3=0;   printf("Welcome to the Dog Races!\n");         printf("You have %d chips.\n",chips);      printf("You can bet on any of eight dogs.\n");      printf("Which dog do you want to bet on?  Select a dog from 1 to 8.\n");      scanf("%d",&dog);      printf("Do you think your dog will win (1), show (2), or place (3)?\n");      scanf("%d",&place);      srand(time(NULL));      num1=rand()%8+1;      num2=rand()%8+1;      num3=rand()%8+1;      printf("Dog number %d won the race!\n", num1);      printf("Dog number %d came in second!\n", num2);      printf("Dog number %d came in third!\n", num3);  ```

I'd greatly appreciate it if anybody could help me out with this, and the faster the better (deadline). Thanks.

#2
November 29th, 2006, 12:47 PM
 ComputerPhreak
Super User

Join Date: Sep 2004
Posts: 648
Time spent in forums: 6 Days 21 h 32 m 25 sec
Reputation Power: 75
You will have to compare the second randomly generated number to one that you previously generated. If they are the same, generate a new random number until they differ. Example:

Code:
```int num1, num2;
num1 = rand() % 8 + 1;
while((num2 = rand() % 8 + 1) && (num1 == num2));```

The syntax may be a bit confusing on that one, but the idea is
num2 = random number
while num2 == num1
num2 = new random number

This is a bit clearer:
Code:
```num2 = rand() % 8 +1;
while(num2 == num1)
num2 = rand() % 8 +1;```

#3
November 29th, 2006, 12:48 PM
 clifford
Contributing User

Join Date: Aug 2003
Location: UK
Posts: 4,977
Time spent in forums: 1 Month 4 Days 5 h 19 m 41 sec
Reputation Power: 1801

Since you have only to pick 3, a brute force approach would probably be adequate:

Code:
```num1=rand()%8+1;

do
{
num2=rand()%8+1;
} while( num2 == num1 ) ;

do
{
num3=rand()%8+1;
} while( num3 == num1 || num3 != num2 ) ;```

Not pretty, or generally applicable, but possibly good enough in this case.

A more general approach might use a container class such as an STL <vector>. Initialise the members of the list sequentially, adding as many as you need - 8 in this case.

Then you pick a random number from 0 to the number of elements in the container less one. Remove that element from the list and use the value it contains. Next time you do this there will be one less element so you cannot select it again. This algorithim works for things like card dealing. You can do it with a simple array, and invalidate entries and then use the random number to count through valid entries.

Clifford

#4
November 29th, 2006, 12:48 PM
 Oler1s
Contributing User

Join Date: Jul 2006
Posts: 2,270
Time spent in forums: 1 Month 2 Weeks 4 Days 15 h 34 m 57 sec
Reputation Power: 1736
Use a loop...Generate an array of pseudo-random numbers, with the array size set to whatever you determine to be the number of dogs in the dog race. Loop through the array with a for loop, each time adding to the array a prn.

When printing the values out to screen, use a loop once more.

A sign that your code is written or structured incorrectly is when you repeat yourself. As you can see, your code repeats itself in generating prns and printing out values.

More importantly, your code is non-compiling and does not express the logic correctly. I assume you realise this and you just needed the above question answered.

EDIT: I need to learn to type faster
__________________
When you ask a question, be prepared to tell us: what have you tried? If you think you don't need to try anything, we will never be interested in helping you. If you agree with the link, and you refuse to answer that question, you are being a hypocrite.

Need help with broken code? Your question should be like a good bug report: (1) It has the smallest number of steps to reproduce the problem you see (2) It tells us precisely what you expected to see and (3) It tells us what you saw and how it differed from what you expected. We need all three to help you.
Want better answers? Tell us what you Googled for and what steps you took to answer your own question.

#5
November 29th, 2006, 12:51 PM
 Omega_1405
Registered User

Join Date: Nov 2006
Posts: 7
Time spent in forums: 1 h 41 m 45 sec
Reputation Power: 0
That worked perfectly. Thanks a bunch.

#6
November 29th, 2006, 01:21 PM
 Omega_1405
Registered User

Join Date: Nov 2006
Posts: 7
Time spent in forums: 1 h 41 m 45 sec
Reputation Power: 0
Quote:
 Originally Posted by Oler1s More importantly, your code is non-compiling and does not express the logic correctly. I assume you realise this and you just needed the above question answered.

I know. I just stuck in the part of the code I was having problems with, instead of tossing the whole thing in here.

#7
November 29th, 2006, 03:14 PM
 salem
Contributed User

Join Date: Jun 2005
Posts: 4,266
Time spent in forums: 2 Months 4 Weeks 1 Day 18 h 35 m 56 sec
Reputation Power: 1827
Fill an array with your desired (possibly non-repeating) sample.
Shuffle it by swapping random pairs of entries in the array - think of how you would shuffle a pack of cards by swapping just two cards at a time.
__________________
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper

#8
November 29th, 2006, 04:46 PM
 Scorpions4ever
Banned ;)

Join Date: Nov 2001
Location: Woodland Hills, Los Angeles County, California, USA
Posts: 9,539
Time spent in forums: 2 Months 3 Days 9 h 9 m 34 sec
Reputation Power: 4106
If you're using C++ and have covered the STL in your class, then you could use the random_shuffle algorithm template to do this .
Code:
```#include <iostream>
#include <algorithm>
using namespace std;

const int num_elems = 20;

void print_array(int *array, int max)
{
for (int i = 0; i < max; i++)
cout << i << " ==> " << array[i] << endl;
}

int main(void)
{
int array[num_elems];

for (int i = 0; i < num_elems; i++)
array[i] = i;

cout << "Before shuffle " << endl;
print_array(array, num_elems);

random_shuffle(&array[0], &array[num_elems]);

cout << endl << endl << "After shuffle " << endl;
print_array(array, num_elems);

return 0;
}```
__________________
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!" - Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Generating multiple nonrepeating random numbers

## Developer Shed Advertisers and Affiliates

 Thread Tools Search this Thread Search this Thread: Advanced Search Display Modes Rate This Thread Linear Mode Rate This Thread: 5 : Excellent 4 : Good 3 : Average 2 : Bad 1 : Terrible

 Posting Rules You may not post new threads You may not post replies You may not post attachments You may not edit your posts vB code is On Smilies are On [IMG] code is On HTML code is Off
 View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox Forum Jump Please select one User Control Panel Private Messages Subscriptions Who's Online Search Forums Forums Home -------------------- Programming Languages    PHP Development        PHP FAQs and Stickies    Perl Programming        Perl FAQs and Stickies    C Programming        C Programming FAQs and Stickies    Java Help        Java FAQs    Python Programming        Python Programming FAQs    Ruby Programming        Ruby Programming FAQs    Game Development        Game Development FAQs Programming Languages - More    ASP Programming        ASP Programming FAQs    .Net Development        .Net Development FAQs    Visual Basic Programming        Visual Basic Programming FAQs    Software Design        Software Design FAQs    ColdFusion Development        ColdFusion Development FAQs    Delphi Programming        Delphi Programming FAQs    Regex Programming        Regex Programming FAQs    XML Programming        XML Programming FAQs    Other Programming Languages        Other Programming Languages FAQs Web Design    HTML Programming        HTML Programming FAQs    JavaScript Development        JavaScript Development FAQs    CSS Help        CSS Help FAQs    Flash Help        Flash Help FAQs    Photoshop Help        Photoshop Help FAQs    Web Design Help        Web Design Help FAQs    Website Critiques        Website Critiques FAQs    Search Engine Optimization        Search Engine Optimization FAQs Mobile Programming    Mobile Programming        Mobile Programming FAQs    iPhone SDK Development        iPhone SDK Development FAQs    Android Development        Android Development FAQs    BlackBerry Development        BlackBerry Development FAQs Web Site Management    Business Help        Business Help FAQs    Development Software        Development Software FAQs    Scripts        Scripts FAQs Databases    Database Management        Database Management FAQs    DB2 Development        DB2 Development FAQs    MySQL Help        MySQL Help FAQs    PostgreSQL Help        PostgreSQL Help FAQs    Firebird SQL Development        Firebird SQL Development FAQs    MS SQL Development        MS SQL Development FAQs    Oracle Development        Oracle Development FAQs    LDAP Programming        LDAP Programming FAQs System Administration    Mail Server Help        Mail Server Help FAQs    Apache Development        Apache Development FAQs    Security and Cryptography        Security and Cryptography FAQs    Antivirus Protection        Antivirus Protection FAQs    DNS        DNS FAQs    IIS        IIS FAQs    Networking Help        Networking Help FAQs    FTP Help        FTP Help FAQs Operating Systems    BSD Help        BSD Help FAQs    Linux Help        Linux Help FAQs    UNIX Help        UNIX Help FAQs    Windows Help        Windows Help FAQs    Mac Help        Mac Help FAQs Web Hosting    Web Hosting        Web Hosting FAQs    Free Web Hosting        Free Web Hosting FAQs    Web Hosting Requests        Web Hosting Requests FAQs    Web Hosting Offers        Web Hosting Offers FAQs Computer Hardware    Computer Hardware    CPUs        CPUs FAQs    Cooling        Cooling FAQs    Embedded Programming        Embedded Programming FAQs    Motherboards        Motherboards FAQs    Multimedia Hardware        Multimedia Hardware FAQs Other    Dev Shed Lounge        Dev Shed Lounge FAQs    Development Articles        Development Articles FAQs    Beginner Programming        Beginner Programming FAQs    Hire A Programmer        Hire A Programmer FAQs    Project Help Wanted        Project Help Wanted FAQs Latest News Updated Hourly    Technology News    Business News    Science News Forum Information    Forum Rules/Guidelines        Forum Rules/Guidelines FAQs    Forum Announcements        Forum Announcements FAQs    Dev Shed Gaming Center        Go to the Dev Shed Battle Arena        Go to the Dev Shed Arcade Games        Go to the Legend of the Green Dragon    Suggestions & Feedback        Suggestions & Feedback FAQs

 Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |