C# .NET - Randomize An Array
Asked By Craig Vedur
12-Dec-05 01:12 PM
Hey,
I have an array and I want to randomize it's contents. I have this algorithm but it seems as though sometimes the array doesn't get shuffled. Any help?
public static ListDTO[] Shuffle(ListDTO[] listDTO)
{
int newIndex;
ListDTO tempListDTO;
try
{
for (int i = 0; i < listDTO.Length; i++)
{
newIndex = new Random().Next(listDTO.Length);
tempListDTO = listDTO[i];
listDTO[i] = listDTO[newIndex];
listDTO[newIndex] = tempListDTO;
}
}
catch (Exception ex)
{
LoggerUtility.GetInstance().ApplicationLogger.Error("Error while shuffling ListDTO objects", ex);
}
return listDTO;
}
You could introduce
a level of Randomness..again by checking that if a number's destination index is the same as its source index..go in a loop and generate the next Random# that is not the same Index as the Source..
public static ListDTO[] Shuffle(ListDTO[] listDTO)
{
int newIndex;
ListDTO tempListDTO;
try
{
for (int i = 0; i < listDTO.Length; i++)
{
newIndex = new Random().Next(listDTO.Length);
while(i!=newIndex)
{
newIndex = new Random().Next(listDTO.Length);
}
tempListDTO = listDTO[i];
listDTO[i] = listDTO[newIndex];
listDTO[newIndex] = tempListDTO;
}
}
catch (Exception ex)
{
LoggerUtility.GetInstance().ApplicationLogger.Error("Error while shuffling ListDTO objects", ex);
}
return listDTO;
}
I added a seed
I changed:
newIndex = new Random().Next(listDTO.Length); to:
newIndex = new Random(i).Next(listDTO.Length);

with all the declaration, without the static keyword. By doing so, I got the link error LNK2019 saying the functions are unresolved externals. The Helper.cpp file is part of the function body to the .h file and comment it out in the .cpp file, the error disappears. Jeova If you use the precompiled headers, make sure that the first non-comment you would never, ever, under any imaginable conditions, want to create a class into which random functions were tossed, willy-nilly, just because they didn't "fit" someplace else, because that other function would ever be added to this compilation unit, UNLESS it directly dealt with error code handling. * ** * * ** * That is ALWAYS a design error. Plunking random functions into a single file makes no sense. It didn't "work fine", it gave was already a bad idea, the idea of helpers.h which was a collection of random functions performing random things on random data types. Trying to emulate a poor design in OO only ends
row 717. My code looks like this. template<typename T> class Singleton { public: static T& getInstance() { return *instance_; } private: typedef volatile T* SPtr; static SPtr instance_; }; template<typename T> typename Singleton<T> ::SPtr Singleton<T> ::instance_; int main() { typedef Singleton<int> S; S::getInstance() = 4711; } But when I compile it with gcc 4.4.1 I get the following error message at 'return *instance_;'. expression of type 'volatile int' " What am I doing wrong? Thanks your code with a not portable construct + usage.) To answer your specific question, why that error message, let us look at your code: *instance is an lvalue of type "volatile T comp.lang.c++.moderated. First time posters: Do this! ] I would suggest: static volatile T& getInstance() { return *instance_; } BTW, remember to initialize instance_ somewhere. HTH, eca - - [ See http: / / www.gotw.ca compiled executable, when run multiple times, can print any of the 4, perhaps changing at random between executions, for a conforming compiler. Without a "happens-before" relationship (to borrow the term but I seem to recall Andrei admitting that he misunderstand volatile, and learned of the error of his ways, possibly in conjunction with "C++ And The Perils Of Double-Checked Locking C++. (He can reply to identify himself if he wishes.) Two years after having an error in Visual C++ reported whereby automatic objects of class type are not destructed in certain
insert the variable names before the brackets for me? char[6] a, b, c, d; / / ERROR Why? Because char[6] is not a C++ type. Period. - Alan Carre Ok, well you expected. The compiler itself tells you that `char[12]' is a type in warnings and error messages. Alex And I accepted his explanation, admitted my mistake and apologized for being rude no need to be an allocated storage for "b". - - best regards Cezary Noweta Hello, Minor error: should be "int Member() const {", but it is obvious. No. The standard (ISOC++2003 9 all. But the problem with this is that it doesn't compile. And the compiler error says this: error C2440: 'return' : cannot convert from 'const int *_ _w64 ' to 'int *' Conversion loses qualifiers For some decides to declare one at global scope then suddenly your whole program flow becomes a random variable. You can't tell which objects are going to be constructed first, or deleted have to make a call to the function before it gets created. Everything just as random as ever (ex. another function contains static with member which calls function that contains static order of construction is in the order that the linker encounters them. Or maybe just random, but I'm guessing the linker. For instance I have this class, and I had
asp:ScriptManager / > control <script language = "javascript"> / / Get the PageRequestManager instance var pageRequest = Sys.WebForms.PageRequestManager.getInstance(); / / Add the beginRequest Event pageRequest.add_beginRequest(beginRequest); / / Add the endRequest Event pageRequest.add_endRequest(endRequest) / / Handle request is about to start $ . ajax ({ url : '. . ' , type : '. . ' , complete : function () { / / request is complete, regardless of error or success, so hide image $ ( '#loading_image' ). hide (); } }); It's not rocket science, I promise. :) EDIT Width = "283px" / > < / ContentTemplate> < / asp:UpdatePanel> in coe behind protected void gettickvalue(object sender, EventArgs e) { Random RandomNumber = new Random(); int n = RandomNumber.Next(1, 8); imgBanner.ImageUrl = System.String.Concat("images / banner_", n.ToString find( 'image' ).each( function () { var fullpath = $( this ).find( 'fullpath' ).text(); obj.push(fullpath); }); start(obj); }, error: function (ex) { alert( "Error on loading xml file" ); } }); function start(obj) { var totalcount = obj.length; setInterval( function () { var counter