gpt4 book ai didi

vb.net - 如何从另一个数组字符串中随机获取数组?

转载 作者:行者123 更新时间:2023-12-01 12:31:35 25 4
gpt4 key购买 nike

我有这个文本数组(颜色)

 Dim ArrayColor As String() = {"Red", "Green", "Yellow", "Blue"}

从这个数组开始,我需要一个新的随机数组并且不要重复颜色。 Ej:

Dim ArrayRandomColor As String() = {"Green", "Yellow","Red" "Blue"}

另一个EJ:

Dim ArrayRandomColor As String() = {"Yellow", "Blue","Green" "Red"}

我正在 vb.net 2010 中开发一款策划“游戏”我首先分配密码

最佳答案

其实我也在玩这个方法。并不是说它是最有效的,因为 GUID...(阅读评论)

' Consider that each of your colors is assigned specific position in sort order
dim d as new dictionary(of integer, string)
d.Add(0,"Green")
d.Add(1,"Red")
d.Add(2,"Blue")
d.Add(3,"Yellow")

' Now we have to create random sort order
Dim colors = Enumerable.Range(0, 4).Select(Function(i) new with {.k = i, .g= Guid.newguid.tostring()}).ToList()
' The line above creates 4 elements with matching keys and unique GUIDs

' since guids are unique and "random", each time when you sort them, your keys will take different positions
' And this will effectively shuffle your colors by dictionary key
for each c in colors.OrderBy(function(x)x.g) ' sort by guid
Console.WriteLine(d(c.k))
next

更新

我再次查看了这个答案,我相信是啤酒喝多了让我写了那段代码。它绝对有效,但可能会更好。首先,您可以在不使用 Dictionary

的情况下编写该想法(使用 GUID)
Dim colors() As String = {"Red", "Green", "Yellow", "Blue"}
' Logic: convert to object with unique GUID, sort by GUID
colors.Select(Function(c) New With { .color = c, .guid = Guid.NewGuid.ToString() }).
OrderBy(Function(c) c.guid).ToList().
ForEach(Sub(item) Console.WriteLine(item.color))

但正如我之前所说,这效率不高。所以,这是更有效的方法。

通常,如果您想随机化少量项目,首先想到的是将它们排序为 1,2,3,4...但是按照这种想法,使用 Random 是一个问题因为 r.Next(1, 5) 可能真的会让你得到 1,1,1,1。这里的想法是,如果你在大范围内随机运行,每个项目两次,并沿途划分数字,你肯定会得到完全随机的数字。

colors.Select(Function(c) new with {.color = c, .num = r.Next(1, 1000000) / r.Next(1, 1000000) }).
OrderBy(Function(c) c.num).ToList().
ForEach(Sub(item)Console.WriteLine(item.color))

经测试,最后一种方法的执行速度提高了两倍。享受吧。

关于vb.net - 如何从另一个数组字符串中随机获取数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882404/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com