简体   繁体   English

随机选择一个数组元素

[英]Randomly select an array element

So I'm trying to select a random element and then save said element, not quite knowing as to how I would go about doing this. 因此,我试图选择一个随机元素,然后保存所说的元素,但我不太了解如何进行此操作。 The first thing that came to mind, although messy to write was: 我想到的第一件事,尽管写得很乱:

Rnd(griddata(1), griddata(2), griddata(...))

I did receive an error however from this: 但是我确实收到了一个错误:

Overload resolution failed because no accessible 'Rnd' accepts this number of arguments. 重载解析失败,因为没有可访问的“ Rnd”接受此数量的参数。

The plan is to store whatever random element it chooses as memory as well. 计划是存储它选择作为内存的任何随机元素。

Any help would be greatly appreciated. 任何帮助将不胜感激。 Thanks! 谢谢!

    Dim myArray() As Integer = {1, 10, 12, 11, 44, 23, 2, 1, 5, 6, 2, 7}
    Dim rnd As New Random
    Dim randomArrayElement = myArray(rnd.Next(0, myArray.Length - 1))

Or even you can try the same from a string also 甚至您也可以从字符串尝试相同的操作

    Dim chars = "0123456789"
    Dim random = New Random()
    Dim result = New String(Enumerable.Repeat(chars, 1).[Select](Function(s) s(randomOtp.[Next](s.Length))).ToArray())
Dim rnd = new Random()
...
Dim randomIndex = rnd.Next(0, griddata.Length)
Dim randomValue = griddata(randomIndex)

This is assuming that your array is 0-based (as .NET arrays usually are). 这是假设您的数组基于0(通常是.NET数组)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM