So I wanted to code a simple PRNG for generating terrain in a game. It has to have the following properties:
Computationally cheap
Generate semi random numbers between 0 and an positive integer.
I need to be able to go back and teleport anywhere in the world so random.Next doesn't cut it.
I basically want a noise function. One output for each input with repeatable results.
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)
)
);
}
}
}
}