Efficiently pick n random elements from PHP array (without shuffle)

$randomArray = []; while (count($randomArray) < 5) { $randomKey = mt_rand(0, count($array)-1); $randomArray[$randomKey] = $array[$randomKey]; } This will provide exactly 5 elements with no duplicates and very quickly. The keys will be preserved. Note: You’d have to make sure $array had 5 or more elements or add some sort of check to prevent an endless … Read more

An extension method on IEnumerable needed for shuffling [duplicate]

You can use a Fisher-Yates-Durstenfeld shuffle. There’s no need to explicitly pass a size argument to the method itself, you can simply tack on a call to Take if you don’t need the entire sequence: var shuffled = originalSequence.Shuffle().Take(5); // … public static class EnumerableExtensions { public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source) { return source.Shuffle(new … Read more

How to shuffle characters in a string without using Collections.shuffle(…)?

I dont know anything simpler. But you can use the Math.rand() functionality to generate a random number within the range of the character’s length without replace and that would give you a shuffled output public class Shuffle { public static void main(String[] args) { Shuffle s = new Shuffle(); s.shuffle(“hello”); } public void shuffle(String input){ … Read more