数组中某个值的随机索引



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

var indexWinnder = Array.IndexOf(scoreArray, nearestScore)

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

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

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

也许你想要这样的东西:

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-

更新

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

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

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

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

如果你真的想要一个随机的,随机并不是最好的选择,因为它遵循一个特定的模式,会一次又一次地发生。如果你想要更随机的东西,你可以看看RNGCryptoService提供程序:https://www.dotnetperls.com/rngcryptoserviceprovider.希望这能有所帮助!

最新更新