Results 1 to 9 of 9

Thread: randomize an array[resolved]

  1. #1

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    randomize an array[resolved]

    how would i randomize an array like for example i have..

    dim this(0 to 9) as string

    this(0) = 0
    this(1) = 1
    this(2) = 2
    this(3) = 3
    this(4) = 4
    this(5) = 5
    this(6) = 6
    this(7) = 7
    this(8) = 8
    this(9) = 9

    and i randomize it and it turns to something like

    this(0) = 5
    this(1) = 3
    this(2) = 2
    this(3) = 1
    this(4) = 6
    this(5) = 0
    this(6) = 7
    this(7) = 4
    this(8) = 9
    this(9) = 8

    can anyone help???
    Last edited by high6; Nov 23rd, 2005 at 01:14 PM.

  2. #2
    PowerPoster
    Join Date
    Aug 2005
    Location
    College Station, TX
    Posts
    4,521

    Re: randomize an array?

    Just to be sure you are indeed needing this... do you actually need to scramble the array in memory, or will just pulling a random index value out of the array work as well?? The reason I ask is that it would probably be easier to pull out a random index number instead of scrambling the entire array...

  3. #3

    Thread Starter
    Frenzied Member
    Join Date
    Sep 2005
    Posts
    1,547

    Re: randomize an array?

    Quote Originally Posted by gigemboy
    Just to be sure you are indeed needing this... do you actually need to scramble the array in memory, or will just pulling a random index value out of the array work as well?? The reason I ask is that it would probably be easier to pull out a random index number instead of scrambling the entire array...
    well...
    i have an app that gets info from a file and puts it into an array and i wanna randomize it and put it back in the file... would wat u mentioned work?

  4. #4
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: randomize an array?

    Yes....sort of. You would have to have some kind of technique to prevent getting the same item twice. There are several ways to do this, depending to some extent on how truly random you need to be. Here's one technique that would be fairly (but not perfectly) random.

    I assume the array has N items in it:

    1) Dim rnd as New Random
    2) For i = 0 to N-1
    3) Random.Next(0,N+1)

    4)Now, the value returned will be an index into the array. That index value has either been written to the file, or it has not. If it HAS NOT been written, write it, then set the array slot to "". If it HAS been written, then the array slot will hold "". At that point:

    5) Get a random number between 0 and 100. If it is less than 50 move down, if it is greater than 50 move up. Assume you are looking up, and the index you start at is 5, you then look at 6, 7, 8, etc. looking for a string that has not been written. When you find one, write it, and clear the slot. If you reach the end of the array, start over at the beginning.

    This sounds like alot of work, but it isn't hard to implement, and has the advantage that it will take only N iterations to move N lines into the file.
    My usual boring signature: Nothing

  5. #5
    PowerPoster 2.0 Negative0's Avatar
    Join Date
    Jun 2000
    Location
    Southeastern MI
    Posts
    4,367

    Re: randomize an array[resolved]

    Something like this:

    VB Code:
    1. ' Create the arrays
    2.         Dim this As New ArrayList
    3.         Dim arrRand As New ArrayList
    4.  
    5.         ' Fill the base array
    6.         For i As Integer = 0 To 9
    7.             this.Add(i)
    8.         Next
    9.  
    10.         Dim rand As New Random
    11.  
    12.         'Randomly remove items from the base array and add them to our random array
    13.         For j As Integer = 0 To 9
    14.             Dim item As Integer
    15.             item = rand.Next(0, this.Count - 1)
    16.             arrRand.Add(this(item))
    17.             this.RemoveAt(item)
    18.         Next
    19.  
    20.  
    21.         'Check the output to see that it is random
    22.         Dim sb As New StringBuilder
    23.         For i As Integer = 0 To 9
    24.             sb.Append(arrRand.Item(i))
    25.         Next
    26.  
    27.         MsgBox(sb.ToString())

  6. #6
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: randomize an array[resolved]

    There is one issue with Negative0's code. Note exactly what the arguments to Random.Next mean. The number returned will be >= the first argument but < the second argument, so this line:
    VB Code:
    1. item = rand.Next(0, this.Count - 1)
    should be:
    VB Code:
    1. item = rand.Next(0, this.Count)
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  7. #7
    Addicted Member rabid lemming's Avatar
    Join Date
    Feb 2005
    Posts
    210

    Re: randomize an array[resolved]

    I know this isn’t vb code but it may be useful to know as perhaps you can apply it to vb

    here is how to pick a set of random numbers from a range of numbers with out picking the same number twice

    This code was developed for java script

    Code:
    // The number of unique random numbers you want to generate, must be less or equal to set max. If you want a set of 10 unique random numbers set a = 10 or what ever you want
    var a = 5;
    // The maximum number you want to randomly generate. So if you wanted to pick 5 unique random numbers between 0 and 10 
    // you would setMax = 10 or what ever you wanted
    var setMax = 10;
    // set up varibles 
    var rNum;
    // Takes into account that computers count 0 as a number so ensure the number of unique random numbers you want is right
    a -= 1;
    // Create an array
    var numArray = new Array(a);
    // Function for creating a set of unique random numbers
    _global.makeNumbers = function() {
    	// for loop
    	for (var i = 0; i<=a; i++) {
    		// Generate a random number
    		rNum = Math.round(Math.random()*setMax);
    		// Another for loop
    		for (var k = 0; k<=a; k++) {
    			// Check if that unique random number has already been picked
    			if (rNum == numArray[k]) {
    				// If it has pick another random number
    				rNum = Math.round(Math.random()*setMax);
    				// Run the check again
    				i = 0;
    			}
    		}
    		// If the unique random number has not already been added, then add it to the array
    		numArray[i] = rNum;
    	}
    }
    // Call the function for generating the unique random numbers
    makeNumbers();
    ....

    The above version is good and works but isnt 100% perfect You see if you wanted to create the numbers 0 to 10 in a random order ensuring no too numbers were ever the same. Then the script above would not work because of the limitations in flash

    You see although the script above and create a list of unique numbers with no too numbers ever being the same the problem is that if you want to create a list say 0 to 10 and want the numbers in that list between 0 and 10 too then because the list length is the same as the range of numbers you’re generating, then flash player can cope with this as the 2 loops in the code tip over each other and cause flash player to crash

    To see what I mean set var a = 10; and var setMax = 10; and player will crash. Now it can handle var a = 3; var setMax = 3; or a little higher depending on the power of you pc but anything higher than var a = 5; and var setMax = 5; then flash player can’t cope as it’s too much for it to calculate and will crash. It works fine so long as the “var a” and “var setMax” are never the same but if they are your find it won’t work.

    So...I came up with a new version that can create a list of random numbers wear no numbers are ever the same, but can be the length of numbers been generated can be the same the range of numbers generated. So if you want a list of numbers from 0 to 10 in random order with no two numbers ever been the same here is how.

    This code was developed for flash

    ...

    I will wait for death with a smile and a big stick

  8. #8
    Addicted Member rabid lemming's Avatar
    Join Date
    Feb 2005
    Posts
    210

    Re: randomize an array[resolved]

    ...

    Code:
    // Declare the function
    function getUniqueRandomNumbers(NumberOFNumbers, IncludeZero, Return, GetArrayIndex) {
    	// Create a new array for sequential number list
    	var numberlist = new Array();
    	// Create a new array for randomised values
    	var randomlist = new Array();
    	// Create a variable
    	var count;
    	// Create a variable
    	var picked;
    	// Check the 'NumberOFNumbers' is a numeric value
    	if (isNaN(""+NumberOFNumbers+"") == true || isNaN(NumberOFNumbers) == true) {
    		// Trace an error message if the 'NumberOFNumbers' is not a numeric value
    		trace("Invalid input, Please check the value input for 'NumberOFNumbers' is a numeric number with out quotes ");
    		// Return the error message if the 'NumberOFNumbers' is not a numeric value
    		return ("Invalid input, Please check the value input for 'NumberOFNumbers' is a numeric number with out quotes ");
    		// If the 'NumberOFNumbers' is a numeric value then do the following
    	} else {
    		// Check the user 'IncludeZero' is a true or false value, if its not either then assume its true or if it is true then do the following
    		if (IncludeZero != true && IncludeZero != false || IncludeZero == true) {
    			// Run a count from 0 to what ever value 'NumberOFNumbers' is
    			for (count=0; count<=NumberOFNumbers; count++) {
    				// Place each value in the array to get: 0,1,2,3,4,5,6,7 etc...
    				numberlist[count] = count;
    			}
    			// Loop from total number of numbers in the array down to zero
    			for (count=numberlist.length-1; count>=0; count--) {
    				// Pick a random number between 0 and the number of random values remaining in the array 'numberlist'
    				picked = Math.floor(Math.random()*count);
    				// Copy the value from the array 'numberlist' that was picked to the second array 'randomlist'
    				randomlist[count] = numberlist[picked];
    				// Remove the number picked from the first array 'numberlist' so it can not be randomly picked again
    				numberlist[picked] = numberlist[count];
    			}
    			// If 'IncludeZero' is set the flase then run the following
    		} else {
    			// Run a count from 1 to what ever value 'NumberOFNumbers' is
    			for (var count = 1; count<=NumberOFNumbers; count++) {
    				// Place each value in the array to get: 1,2,3,4,5,6,7 etc...
    				numberlist[count] = count;
    			}
    			// Loop from total number of numbers in the array down to zero
    			for (count=numberlist.length-1; count>0; count--) {
    				// Pick a random number between 0 and the number of random values remaining in the array 'numberlist'
    				picked = Math.floor(Math.random()*count)+1;
    				// Copy the value from the array 'numberlist' that was picked to the second array 'randomlist' in the next array cell slot along
    				randomlist[count-1] = numberlist[picked];
    				// Remove the number picked from the first array 'numberlist' so it can not be randomly picked again
    				numberlist[picked] = numberlist[count];
    			}
    		}
    		// Check to see if the 'Return' is a numeric value
    		if (isNaN(""+Return+"") == true || isNaN(Return) == true) {
    			// If it is not set or not a number then send all of the resulting array back
    			return (randomlist);
    			// Check to see if the user wants to return any particular part of the array
    		} else if (GetArrayIndex == true) {
    			// If they do return that part of the array value
    			return (randomlist[Return]);
    		} else {
    			// If it is set or not a number then send back only the part of the array the user wants
    			return (randomlist.slice(0, Return));
    		}
    	}
    }
    // Call the function and get the values
    var Ans = getUniqueRandomNumbers(10, true, 11, false);
    
    /* READ ME ALL 
    
    To call the function:
    getUniqueRandomNumbers(Option 1, Option 2, Option 3, Option 4);
    
    Option 1 = Set how many numbers you want to generate i.e. If you wanted 5 unique numbers you would put 5 here with out quotes. You must set this value 
    
    Option 2 = Set weather to include 0 or not in the numbers generated. You can leave this out and the code will assume to include 0 
    
    Option 3 = Set how many numbers to return i.e. if you generate 10 unique numbers but only want to get back 5 of those numbers then set this to 5 with out quotes. 
    You can leave this out and the code will assume you want all the unique numbers returned. You must ignore the next option if you want to return a specific 
    number of randomly generated unique numbers from the function. You must set this option if you wish to use the next option
    
    Option 4 = You can set weather to return a particular array value i.e. MyVar = getUniqueRandomNumbers(10, true, 10, true); will retune the unique random number value 
    from the 10th array cell only. You can leave this out. You must ignore this option if you want to return a specific number of randomly generated 
    unique numbers from the function. The previous option must be set as a number with out quotes to use this option 
    
    Examples:
    
    Example 1:
    Method 1: var MyVar = getUniqueRandomNumbers(10);
    Method 2: var MyVar = getUniqueRandomNumbers(10, true);
    Method 3: var MyVar = getUniqueRandomNumbers(10, true, 11);
    // Either of these will return all the numbers 0 to 10 in a random order, with all the numbrs been unique. 
    // NOTE: In Method 3, although you are only generating numbers from 0 to 10 you must call back 11 numbers 
    // as if you count 0 as 1 then their are actually 11 numbers when counting from 0 to 10
    
    Example 2:
    Method 1: var MyVar = getUniqueRandomNumbers(10, false);
    Method 2: var MyVar = getUniqueRandomNumbers(10, false, 10);
    // Either of these will return all the numbers 1 to 10 in a random order, with all the numbrs been unique. 
    // NOTE: In Method 2, zero will not be included in the numbers generated so you call back 10 as when counting from 1 to 10 their are 10 numbers
    
    Example 3:
    Method 1: var MyVar = getUniqueRandomNumbers(10, true, 5);
    Method 2: var MyVar = getUniqueRandomNumbers(10, false, 5);
    // Either of these will return only 5 of  the numbers generated 
    // The first method may include the number 0 the second method will not
    
    Example 4:
    Method 1: var MyVar = getUniqueRandomNumbers(5, true, 7, true);
    Method 2: var MyVar = getUniqueRandomNumbers(5, false, 7, true);
    // Either of these will return only 1 number from the 5th cell of the array 
    // The first method may include the number 0 the second method will not
    
    Other examples:
    var MyVar = getUniqueRandomNumbers(0, false, 7, true);
    // Will get the random unique number in the cell index 0 
    var MyVar = getUniqueRandomNumbers(1, false, 7, true);
    // Will get the random unique number in the cell index 1
    var MyVar = getUniqueRandomNumbers(2, false, 7, true);
    // Will get the random unique number in the cell index 2
    var MyVar = getUniqueRandomNumbers(3, false, 7, true);
    // Will get the random unique number in the cell index 3
    // All these will not include zero
    etc…
    */
    Although their not vb code i think you could adapt the code or at least the principals to vb to get the same result

    I will wait for death with a smile and a big stick

  9. #9
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: randomize an array[resolved]

    Randomising an existing array, using essentially the same technique as Negative0:
    VB Code:
    1. Dim myRandom As New Random
    2. Dim myArrayList As New ArrayList
    3. Dim randomIndex As Integer
    4.  
    5. myArrayList.AddRange(existingArray)
    6.  
    7. For i As Integer = 0 To existingArray.Length - 1 Step 1
    8.     randomIndex = myRandom.Next(0, myArraylist.Count)
    9.     existingArray(i) = myArrayList(randomIndex)
    10.     myArrayList.RemoveAt(randomIndex)
    11. Next i
    Note that this code would need modification if it was to be used with reference types.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

Posting Permissions

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



Click Here to Expand Forum to Full Width