Thread: Shuffle elements in an array with duplicates

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    1

    Question Shuffle elements in an array with duplicates

    Hi, I'm new here and am trying to write a c program that shuffles elements in an array in a random order. I have shuffled them in random order but I now require to not have the same two elements side by side in the array. How can I do this?

    Code:
    for(i=1; i<10; i++){		
    		
    		j = rand()%(i+1);
    		strcpy(t, s[j]);
    		strcpy(s[j], s[i]);
    		strcpy(s[i], t);
    		
    		sscanf(s[i-1],"%s, %*s, %*s, %*s", type_1);
    		sscanf(s[i],"%s, %*s, %*s, %*s", type);
    		
    		printf("%s\n", type_1);
    		printf("%s\n\n", type);
    		
    		if((strcmp(type_1, type)) == 0){
    			
    			printf("YESSSS");
    			j = rand()%(i+1);
    			sscanf(s[j],"%s, %*s, %*s, %*s", type_2);
    			
    			while(strcmp(type_2, type) == 0){
    				printf("\n\nentered\n\n");
    				j = rand()%(i+1);
    				sscanf(s[j],"%s, %*s, %*s, %*s", type_2);
    			}
    			
    			strcpy(t, s[j]);
    			strcpy(s[j], s[i]);
    			strcpy(s[i], t);
    			
    			
    		}
    		
    		
    		
    		
    	}

  2. #2
    Registered User
    Join Date
    Jun 2015
    Posts
    1,643
    Your code is wacky. I can't really understand it. And your use of sscanf indicates some misunderstanding (certainly the %*s parts are not necessary, and the initial %s will read the comma as well if there's no space between it and the previous characters).

    Still, the problem is interesting. If you don't have many duplicates in your data and you don't care too much about efficiency you could just scan for consecutive duplicates and if you find one, reshuffle and rescan, etc.

    Obviously, you could also randomly reorder one of the consecutive duplicates, which would presumably be more efficient.

    The problem is not solvable in general, e.g., 1, 1, 1, 2 doesn't have a permutation with no consecutive duplicates.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Shuffle rows in an array
    By Justin Time in forum C Programming
    Replies: 2
    Last Post: 04-23-2015, 07:39 PM
  2. String Array Shuffle
    By omGeeK in forum C Programming
    Replies: 3
    Last Post: 02-14-2011, 07:48 PM
  3. shuffle 2-dimensional array
    By patkhor in forum C Programming
    Replies: 5
    Last Post: 11-26-2008, 03:51 PM
  4. Array Shuffle
    By ypramesh in forum C Programming
    Replies: 2
    Last Post: 04-08-2006, 11:01 AM
  5. Array with at most n duplicates
    By kratz in forum C++ Programming
    Replies: 19
    Last Post: 07-16-2005, 11:46 PM

Tags for this Thread