Skip to main content
2 of 7
edited title
t3chb0t
  • 44.7k
  • 9
  • 84
  • 191

Using hashing to create a PRNG with seed

So I wrote this code to generate a pseudo random number based on an integer. I want to use it for generating terrain in a game. Someone said I should try out hashing so that's what I did. The code is short and works but I'm pretty sure there is a better way. I'm a beginner so any tips are welcome.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Threading;
using System.Security.Cryptography;

namespace Hashing_Functions
{
    class Program
    {
        static void Main(string[] args)
        {
            int i0 = 0;


            while (true)
            {
                i0++;                
                Console.WriteLine(RandomHashFunction(i0, 10));
                //returns random number between 0 and max based on input
            }
        }

        static int RandomHashFunction(int input, int max)
        {
            var SHA1 = new SHA1CryptoServiceProvider();
            StringBuilder sb = new StringBuilder();
            string hash2string;
            double output;
            byte[] hash;
            SHA1.ComputeHash(ASCIIEncoding.ASCII.GetBytes(input.ToString()));
            hash = SHA1.Hash;
            sb.Clear();

            foreach (byte b in hash)
            {
                sb.Append(b.ToString());
            }
            hash2string = sb.ToString();
            output = hash2string.GetHashCode();
            output = Math.IEEERemainder(output, max);
            output = Math.Abs(output);
            
            return Convert.ToInt16(output);
        }
    }
}
Wagacca
  • 179
  • 1
  • 1
  • 7