Random index of a value in an array

Viewed 613

In my program, I have a function that finds the nearest index to an integer.

var indexWinnder = Array.IndexOf(scoreArray, nearestScore)

But the way that Array.IndexOf works is it finds the first match and uses that. I want a random index. Not the first. not the last. Is there any way I can do this?

3 Answers

There is no built-in method for that, but you could use your own method instead. My example uses a generic version of possible implementation.

class Program
{
    static void Main(string[] args)
    {
        var arr = new int[] { 1, 2, 3, 1, 1, 5, 2, 6, 1 };

        var randomIndex = RandomIndexOf(arr, 1);

        Console.WriteLine(randomIndex);
        Console.ReadKey();
    }

    static int RandomIndexOf<T>(ICollection<T> arr, T element)
    {
        var indexes = arr.Select((x, i) => new { Element = x, Index = i })
            .Where(x => element.Equals(x.Element))
            .Select(x => x.Index)
            .ToList();

        if (indexes.Count == 0) // there is no matching elements
        {
            return -1;
        }

        var rand = new Random();
        var randomIndex = rand.Next(0, indexes.Count);

        return indexes[randomIndex];
    }
}

Maybe something like this is what you want:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] sampleArray = new int[] { 1, 2, 3, 2, 1, 3, 1, 2, 3 };

        var indices = getAllIndices(sampleArray, i => i == 2);
        var rnd = new Random();
        var i = rnd.Next(0, indices.Count());
        var randomIndex = indices.ElementAt(i);

        Console.WriteLine(randomIndex);
        Console.ReadLine();
    }

    static IEnumerable<int> getAllIndices(int[] array, Predicate<int> predicate)
    {
        for (var i = 0; i < array.Length; i++)
        {
            if (predicate(array[i]))
                yield return i;
        }
    }
}

HTH

Update

Don't forget to check for empty arrays, null arguments etc.

I dont know if i understood your problem right but if u just want a random index you could write a method and use:

Random rnd = new Random();
int index = rnd.Next(MinValue, MaxValue); // e.g: MinValue: 0, MaxValue: Length of the Array

and then just use that index as the array index.

Random isnt the best option if u really want a random one because it follows a specific pattern that will occur again and again and again. If u want something even more Random you could look into RNGCryptoServiceProvider: https://www.dotnetperls.com/rngcryptoserviceprovider. Hope this helps!

Related