Shuffling an array
CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10

Thread: Shuffling an array

Threaded View

  1. #1
    Join Date
    Jan 2009
    Posts
    16

    Shuffling an array

    I have created a function that is supposed to shuffle the values in an array, I am having issues though - it doesn't seem to shuffle very well and I'm looking for some insight about how to go about it better.

    Code:
    void shuffle(int* a, int size){
    	srand((unsigned)time(0)); 
    
    	for (int i = 0; i < (size-1); ++i) {
            int r = i + (rand() &#37; (size-i)); // Random remaining position.
            int temp = a[i]; a[i] = a[r]; a[r] = temp;
        }
    }
    By not shuffling very well, I mean that I will frequently get the same result twice in a row.

    EDIT

    I also came up with this:
    Code:
    void shuffle(int* a, int size){
    	srand((unsigned)time(0)); 
    
    	for (int i = 0; i < (size-1); ++i) {
            double x=rand()/(RAND_MAX+1.0);
    		int r = (int)(x * (size - 1));
    		int temp = a[i]; a[i] = a[r]; a[r] = temp;
        }
    }
    it works well. Still, I'd like to see suggestions if anyone has any.

    Thanks!
    Last edited by Lang; April 2nd, 2009 at 01:43 AM.

Tags for this Thread

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