arrays - How to solve Randomize in place algorithm in C#? -


i'm reading introduction algorithms - third edition , now, have implement randomize-in-place algorithm must permute each value current array. pseudocode provided book looks this:

n = a.length = 1 n swap a[i] a[random(i, n)] 

i tried implement on c#, i'm receiving indexoutofrangeexception (only in cases). used debug algorithm , found when

randomvalue = array[randomnumber.next(index, upperbound)]; 

index equal array.length - 1 , upperbound array.length - 1 (in other words index , upperbound same values , .next looks .next(9, 9) example), random generator able produce number 10 (lower bound / upper bound + 1) array.length. if has idea how fix helpful me. thank again. here c# code.

namespace randomizedalgorithms {  using system;  class randomizeinplace {     static void main()     {         int[] array = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };         randomize(array);          (int index = 0; index <= array.length - 1 ; index++)         {             console.writeline(array[index]);         }     }      private static void randomize(int[] array)     {         random randomnumber = new random();         int swapvariable = 0;         int randomvalue = 0;         int upperbound = array.length - 1;          (int index = 0; index <= array.length - 1 ; index++)         {             randomvalue = array[randomnumber.next(index, upperbound)];             swapvariable = array[randomvalue];             array[randomvalue] = array[index];             array[index] = swapvariable;         }     } } 

}

you need store random index of element going swap, rather array value itself:

private static void randomize(int[] array) {     random randomnumber = new random();     int swapvariable = 0;     int randomindex;                // <-- renamed     int upperbound = array.length;  // <-- see comments      for(int index = 0; index < array.length; index++)     {         // note: besides minor changes above, real fix removing array[...]         randomindex = randomnumber.next(index + 1, upperbound);         swapvariable = array[randomindex];         array[randomindex] = array[index];         array[index] = swapvariable;     } } 

i've changed code little possible, other improvements possible. note version allows element "swapped" itself, may or may not want.


Comments

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -