How to iterate over an Array/List/IEnumerable the full range of UInt32 in Random order?

StackOverflow https://stackoverflow.com/questions/19307690

  •  30-06-2022
  •  | 
  •  

Question

I've tried several ways, but haven't found what I need.

My goal: run a function with each possible value of an UInt32 and record the result.

The order of uints shouldn't matter, but I would prefer non-sequential.

Any ideas?

These are some that I tried:

for ( var u = UInt32.MinValue; u < UInt32.MaxValue; u++ ) { Debug.WriteLine( u ); } //works, but sequential

var list = Enumerable.Range( Int32.MinValue, Int32.MaxValue ).Select( i => ( UInt32 ) i );  //works, but sequential

var list = Enumerable.Range( Int32.MinValue, Int32.MaxValue ).OrderBy( o => rnd.Next() ).Select( i => ( UInt32 ) i );  //OutOfMemoryException because of the OrderBy

I also tried allocating an array and swapping all the elements, but I don't have that code handy. But it also threw a OutOfMemoryException.

The next tactic I'm going to look at it chunking up the UInt32 range into manageable chunks.

The next tactic after that is populating a sql table and seeing how long a random sort would take.

I'm hoping someone has a helpful hint.

EDIT: Ilya Bursov's idea might work.. Thank you!

Was it helpful?

Solution

Maybe something like this, not random, but at least non sequential and covers full range:

UInt32 i = 0;
do
{
    UInt32 newIndex = ((i & 0xffff) << 16) | (i >> 16); // swap 2 high bytes with 2 low bytes
    // do something with element in array at index newIndex
    i++;
} while (i != 0);

OTHER TIPS

This does it in sequential order, but this would work:

        for (uint i = UInt32.MinValue; i < UInt32.MaxValue; ++i)
        {
            ...
        }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top