How can I best generate a static array of random number on demand?

后端 未结 8 798
北海茫月
北海茫月 2021-01-14 06:56

An application I\'m working on requires a matrix of random numbers. The matrix can grow in any direction at any time, and isn\'t always full. (I\'ll probably end up re-imple

8条回答
  •  不思量自难忘°
    2021-01-14 07:10

    I think your first idea of instantiating a new Random object seeded by some deterministic hash of (x-coordinate, y-coordinate, LazyRandomMatrix seed) is probably reasonable for most situations. In general, creating lots of small objects on the managed heap is something the CLR is very good at handling efficiently. And I don't think Random.ctor() is terribly expensive. You can easily measure the performance if it's a concern.

    A very similar solution which may be easier than creating a good deterministic hash is to use two Random objects each time. Something like:

    public int this[int x, int y]
    {
        get
        {
            Random r1 = new Random(_seed * x);
            Random r2 = new Random(y);
            return (r1.Next() ^ r2.Next());
        }
    }
    

提交回复
热议问题