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

后端 未结 8 796
北海茫月
北海茫月 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:12

    Here is a solution based on a SHA1 hash. Basically this takes the bytes for the X, Y and Seed values and packs this into a byte array. Then a hash for the byte array and the first 4 bytes of the hash used to generate an int. This should be pretty random.

    public class LazyRandomMatrix 
    {
      private int _seed;
      private SHA1 _hashProvider = new SHA1CryptoServiceProvider();
    
      public LazyRandomMatrix(int seed)
      {
        _seed = seed;
      }
    
      public int this[int x, int y]
      {
        get
        {
          byte[] data = new byte[12];
          Buffer.BlockCopy(BitConverter.GetBytes(x), 0, data, 0, 4);
          Buffer.BlockCopy(BitConverter.GetBytes(y), 0, data, 4, 4);
          Buffer.BlockCopy(BitConverter.GetBytes(_seed), 0, data, 8, 4);
    
          byte[] hash = _hashProvider.ComputeHash(data);
          return BitConverter.ToInt32(hash, 0);
        }
      }     
    }
    

提交回复
热议问题