GIDForums  

Go Back   GIDForums > Computer Programming Forums > C Programming Language
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 18-May-2005, 11:29
Toriac Toriac is offline
New Member
 
Join Date: May 2005
Posts: 2
Toriac is on a distinguished road

Random pick from array?


Hey, I'm writing a program for my C++ class and one of the requirements is an array. I found a way to incorporate an array assuming that you can randomly pick items from it. My question to you guys is, is it possible? If so, can you give an example?
  #2  
Old 18-May-2005, 11:44
Dr. Evil Dr. Evil is offline
Member
 
Join Date: Oct 2004
Location: Netherlands
Posts: 120
Dr. Evil will become famous soon enough
CPP / C++ / C Code:
//arr = array, random = random array element
srand(time(NULL));
random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))];
//or if you know the size: arr[rand() % size]
Just so you know, you only need to call srand() once in your program, as proceeding rand()s use the value of the preceeding one as a seed.
  #3  
Old 18-May-2005, 11:49
Toriac Toriac is offline
New Member
 
Join Date: May 2005
Posts: 2
Toriac is on a distinguished road
Quote:
Originally Posted by Dr. Evil
CPP / C++ / C Code:
//arr = array, random = random array element
srand(time(NULL));
random = arr[rand() % (sizeof(arr) / sizeof(arr[0]))];
//or if you know the size: arr[rand() % size]
Just so you know, you only need to call srand() once in your program, as proceeding rand()s use the value of the preceeding one as a seed.

Thanks a lot. This is exactly what I was looking for.
 
 

Recent GIDBlogOnce again, no time for hobbies by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

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
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Merge and Heap...which is really faster silicon C++ Forum 0 10-May-2005 14:46
Sorting Algorithms by Time silicon C++ Forum 4 02-May-2005 22:54
Help with an array using pointers glulu76 C++ Forum 1 01-May-2005 12:21
template comiling problems - need expert debugger! crq C++ Forum 1 01-Feb-2005 22:26

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 21:16.


vBulletin, Copyright © 2000 - 2009, Jelsoft Enterprises Ltd.