Skip to main content
5 of 7
added improved code and samples, also better explanation of what I wanted to achieve
Wagacca
  • 179
  • 1
  • 1
  • 7

Using hashing to create a PRNG with seed

So I wanted to code a simple PRNG for generating terrain in a game. It has to have the following properties:

  1. Computationally cheap

  2. Generate semi random numbers between 0 and an positive integer.

  3. I need to be able to go back and teleport anywhere in the world so random.Next doesn't cut it.

  4. I basically want a noise function. One output for each input with repeatable results.

  5. No seed will be used. If I need another series I'll just shift x value by a couple of millions

These are some outputs produced by my program:

1 as input (x) gives 2 as a pseudo random number

2 as input (x) gives 2 as a pseudo random number

Here's the improved version with more readable variables. Also, is there a better solution that fits all my requirements?

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 x = 0;
            while (true)
            {
                x++;                
                Console.WriteLine(x + " as input gives "+ RandomHashFunction(x, 10));
                //returns random number between 0 and max based on input
            }
        }
        static int RandomHashFunction(int input, int max)
        {
            using (var sha1 = new SHA1CryptoServiceProvider()) // Disposing things is a good habit
            {
                var ascii = ASCIIEncoding.ASCII;
                var hashAsString = ascii.GetChars(
                    sha1.ComputeHash(
                        ascii.GetBytes(input.ToString())
                    )
                );
                return Convert.ToInt32(
                    Math.Abs(
                        Math.IEEERemainder(hashAsString.GetHashCode(), max)
                    )
                );
            }
        }
    }
}
Wagacca
  • 179
  • 1
  • 1
  • 7