数组中值的随机索引

时间:2020-02-27 18:19:42

标签: c# arrays .net indexof

在我的程序中,我有一个函数可以找到最接近整数的索引。

var indexWinnder = Array.IndexOf(scoreArray, nearestScore)

但是Array.IndexOf的工作方式是找到第一个匹配项并使用它。我想要一个随机索引。不是第一个。不是最后的。有什么办法可以做到吗?

3 个答案:

答案 0 :(得分:1)

没有内置方法,但是您可以使用自己的方法。我的示例使用了可能实现的通用版本。

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];
    }
}

答案 1 :(得分:0)

也许您想要这样的东西

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

更新

不要忘记检查空数组,空参数等。

答案 2 :(得分:-1)

我不知道我是否正确理解了您的问题,但是如果您只是想要一个随机索引,则可以编写一种方法并使用:

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

然后仅使用该索引作为数组索引。

如果您真的想要一个随机的随机数,它不是最好的选择,因为它遵循一种特定的模式,这种模式会一次又一次地出现。如果你想要更多随机的东西,你可以看看 RNGCryptoServiceProvider:https://www.dotnetperls.com/rngcryptoserviceprovider。 希望这会有所帮助!