Skip to content

Instantly share code, notes, and snippets.

@mrwellmann
Created October 26, 2016 16:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrwellmann/adf76f081ba9a2a33e8bddb322b74e9d to your computer and use it in GitHub Desktop.
Save mrwellmann/adf76f081ba9a2a33e8bddb322b74e9d to your computer and use it in GitHub Desktop.
Random distinct integers for Unity
using UnityEngine;
public static class RandomDistinctIntegers
{
/// <summary>
/// Generates distinct integers.
/// The Integers inside the array are not randomized. If n = range;
/// This Algorithm works good for a lager amount of numbers and uses less memory than Fischer.
/// Source: https://visualstudiomagazine.com/articles/2013/07/01/generating-distinct-random-array-indices.aspx
/// </summary>
/// <param name="size"> Number of distinct values to generate.</param>
/// <param name="range"> Range between of intergers is between 0 and range-1. Inclusive 0 and range-1.</param>
/// <returns>Integer array with length of range and distinct integers for each index.</returns>
public static int[] DisitnctRandomIntegersReservoir(int size, int range)
{
int[] result = new int[size];
for (int i = 0; i < size; ++i)
result[i] = i;
for (int t = size; t < 5; ++t)
{
int m = Random.Range(0, t + 1);
if (m < size) result[m] = t;
}
return result;
}
/// <summary>
/// Generates distinct integers.
/// The Fisher method is a reasonable choice to generate distinct, random array indices when the range value is not too large
/// (say, under 1,000). But when the value of range is very large, and you're working on a device with limited memory,
/// the memory storage required for the all array may not be available or may lead to poor performance.
/// Source: https://visualstudiomagazine.com/articles/2013/07/01/generating-distinct-random-array-indices.aspx
/// </summary>
/// <param name="size"> Number of distinct values to generate.</param>
/// <param name="range"> Range between of intergers is between 0 and range-1. Inclusive 0 and range-1.</param>
/// <returns>Integer array with length of range and distinct integers for each index.</returns>
public static int[] DisitnctRandomIntegersFischer(int size, int range)
{
int[] result = new int[size];
int[] all = new int[range];
for (int i = 0; i < all.Length; ++i)
all[i] = i;
for (int i = 0; i < all.Length; ++i)
{
int r = Random.Range(i, range);
int tmp = all[r];
all[r] = all[i];
all[i] = tmp;
}
for (int i = 0; i < size; ++i)
result[i] = all[i];
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment