Skip to content

Commit

Permalink
added random extension for Arrays
Browse files Browse the repository at this point in the history
  • Loading branch information
omegaleo committed May 11, 2024
1 parent 4b16454 commit c27575e
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions Runtime/Extensions/ArrayExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using UnityFlow.DocumentationHelper.Library.Documentation;

namespace OmegaLeo.Toolbox.Runtime.Extensions
Expand All @@ -16,5 +18,48 @@ public static T Next<T>(this T[] array, ref int currentIndex)
{
return array[currentIndex++ % array.Length];
}

/// <summary>
/// Method to obtain a random element from inside a list
/// </summary>
/// <param name="array"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Random<T>(this T[] array)
{
if (array.Length == 0) return default;

// Updated based on Robin King's tip about random items https://twitter.com/quoxel/status/1729137730607841755/photo/1
int seed = (int)DateTime.Now.Ticks;

var r = UnityEngine.Random.Range(0, array.Length);

var returnValue = array[r];

return returnValue ?? array.FirstOrDefault();

}

/// <summary>
/// Method to obtain <paramref name="count"/> elements from inside a list
/// </summary>
/// <param name="array"></param>
/// <param name="count"></param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static T[] Random<T>(this T[] array, int count = 1)
{
if (count <= 0) throw new ArgumentOutOfRangeException(nameof(count));

List<T> values = new List<T>();

for (int i = 0; i < count; i++)
{
values.Add(array.Where(x => !values.Contains(x)).ToList().Random());
}

return values.ToArray();
}
}
}

0 comments on commit c27575e

Please sign in to comment.