I’m new to stack overflow and I’m learning a new language which is vb.net. I’m working on a first app that need the use of a database, and what i’m trying to do is taking every entries in a column, putting them in an array, suffle the array and then putting back the new array in the column of the database. Sort of a names in a hat application.. I don’t have any code right now, I’m doing my lessons first and I do search many forums and I have already many pieces of the puzzle like the randomize array, database handling.. My problem is that I don’t find any code to prevent data to get the same order after the shuffle for an example:
Let’s pretend I have 4 entries in my database:
Sarah, james, alex, daniel.
When suffling the array, how can I prevent sarah to comes first, and or james second, etc..
If you could just give me a point to start.. As I told you I’m starting to learn this language and I don’t want you guys to write the app for me but just having a little clue will be much apreciate. I check lessons online but I’m getting a little bored with begginers course and the “hello world” first app demonstration so.. I think I’m ready for the next step!
@Steven got a valid point. But I think you can even go without adding the
SortIndex, because you can shuffle results directly in your query, like this (assuming your backend is MSSQL):If still necessary, here is how an array can be shuffled programmatically:
If you want to make sure original order is not repeated for any of the elements, use this code instead:
Here the most important part is where the item before the last one is forced to be the last item, if the last item was not already picked. This is to make sure last item goes somewhere except the last position, otherwise there is nothing to pick from in the last step. Overall, the sequence appears to be randomly sorted and it’s guaranteed that item #1 will not be #1, #2 will not be #2 etc. The algorithm always ends in N steps, where N is the number of items.