Results 1 to 2 of 2

Thread: Shuffling Help

  1. #1
    KnivesACE is offline Member
    Join Date
    Oct 2008
    Posts
    1
    Rep Power
    0

    Default Shuffling Help

    I have a bit of a problem. I'm trying to create a program that takes a user defined integer from the command line N and shuffles the integer from 0 through N.

    The problem I have, is that the integers must not follow each other. Meaning, 4 does not follow 5, and 8 does not follow 7. I've created the program so that it shuffles the integers, then prints them out. However, I cannot seem to figure out the trouble I am having. Any help would be appreciated.


    Java Code:
    public class Shuffle {
        public static void main(String[] args) {
    
    	int N = Integer.parseInt(args[0]);
    
    	
    	int[] song = new int[N];
    	for (int position = 0; position < N; position++) {
    	    int list = position;
    	    song[position] = list;
    	}
    
    	for (int current = 0; current < N; current++) {
    	    int swap = current + (int) (Math.random() * (N - current));
    	    int tempSong = song[current];
    	    song[current] = song[swap];
    	    song[swap] = tempSong;
    	    System.out.print(song[current] + " ");
    	}
    
    	System.out.println();
        }
    }
    This is an example of what it currently prints out.
    Java Code:
    java Shuffle 10
    2 1 3 8 6 7 9 0 4 5
    I would need to fix it so that 2, doesn't follow or come before 1. 6 before or after 7, etc.


    Thanks!

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    Write the logic to test each element in the array to see if its neighbors are "near" it. If they are, move them some where else.

    What logic do you have in the code you've posted? That's where comments are used to describe what your logic is. I don't see them.

Posting Permissions

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