Skip to content

Instantly share code, notes, and snippets.

@kurtdekker
Created April 25, 2022 19:52
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 kurtdekker/6f9c33ad653d0feac22838225ba21c6c to your computer and use it in GitHub Desktop.
Save kurtdekker/6f9c33ad653d0feac22838225ba21c6c to your computer and use it in GitHub Desktop.
using UnityEngine;
// @kurtdekker
//
// ultra-simple core of "shuffle and pick"
//
// drop this on a blank GameObject and run
public class ShuffleAndPick : MonoBehaviour
{
void PerformShuffleAndPick()
{
// however you want to initialize this, have
// ONE copy of each thing in it:
// source data
int[] things = new int[] { 1, 3, 4, 10, 22, 33, 199, 2000, };
// shuffle
for (int i = 0; i < things.Length; i++)
{
int j = Random.Range(i, things.Length);
var t = things[i];
things[i] = things[j];
things[j] = t;
}
// how much do we want?
int count = 3;
// safety
if (count > things.Length)
{
Debug.LogWarning("You want " + count + " items but I only have " + things.Length);
count = things.Length;
}
// somewhere to store the final output
int[] finalResult = new int[count];
// pick
for (int i = 0; i < count; i++)
{
var thing = things[i];
finalResult[i] = thing;
}
// ONLY do this if you need them in ascending order:
System.Array.Sort(finalResult);
// announce
Debug.Log("I choose these " + count + " things:");
// display items
for (int i = 0; i < finalResult.Length; i++)
{
int result = finalResult[i];
Debug.Log(result.ToString());
}
}
private void Start()
{
PerformShuffleAndPick();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment