首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >随机化字符串数组

随机化字符串数组
EN

Stack Overflow用户
提问于 2016-02-17 22:31:36
回答 2查看 65关注 0票数 0

编辑:这与随机化数字无关。当我尝试这样做的时候,我得到的只是数字,而不是我的字符串。至少有人能解释一下Fisher-Yates-shuffle或者它是什么,在我的例子中是如何工作的,如果它确实对句子字符串有效的话?因为我不明白..我不能是唯一一个不理解它的人?

我有一个想要随机化的字符串数组。我想要三个随机字符串,它们不一样,但我在网上找到的所有东西要么是数字,要么是另一种语言。目前我的字符串是随机的,但有时我会得到相同的字符串,例如:“在树后面,在树后面,在树后面”。

所以它应该像randomHiding1 != randomHiding 2 && randomHiding3;(我知道这不是“真正的代码”,但你应该明白我的意思)

这是我在这里的第一篇文章,所以我希望这是可以问的,因为我还没有找到任何人问关于随机化“句子-字符串”的问题,而不仅仅是“abcdefg……”。或者是数字。这是我的代码。提前感谢!

代码语言:javascript
复制
    Random random = new Random();

    // strings with hiding spots
        string[] hidingSpot = {
            "in a ditch",
            "up in a tree",
            "behind a stone",
            "in a hole in the ground",
            "behind a tree",
            "in the shadows" };

        int hidingChoice1 = random.Next(hidingSpot.Length);
        int hidingChoice2 = random.Next(hidingSpot.Length);
        int hidingChoice3 = random.Next(hidingSpot.Length);

        string randomHiding1 = hidingSpot[hidingChoice1];
        string randomHiding2 = hidingSpot[hidingChoice2];
        string randomHiding3 = hidingSpot[hidingChoice3];

顺便说一句,我知道这段代码非常糟糕,而且不必要地冗长,但我对数组和列表仍然相当陌生,所以我的首要任务是获得能够工作的代码,而不是简短的代码等等。所以我不需要阅读文档的提示,因为我经常这样做,但由于个人原因,我很难记住一些东西。我希望这是有意义的。

EN

回答 2

Stack Overflow用户

发布于 2016-02-17 22:36:35

也许这对你有帮助:Fisher-Yates Shuffle

票数 0
EN

Stack Overflow用户

发布于 2016-02-17 22:39:40

使用LINQ的方法:

代码语言:javascript
复制
Random r = new Random();
string[] hidingSpot = "in a ditch|up in a tree|behind a stone|in a hole in the ground|behind a tree|in the shadows".Split('|');
hidingSpot = hidingSpot.OrderBy(x => r.Next()).ToArray();
string one = hidingspot[0];
string two = hidingspot[1];
string three = hidingspot[2];

最后:

正如Stefan Schmid在另一个答案中提到的,您可以实现Fisher-Yates Shuffle,也称为Knuth Shuffle。这里提供了一个实现,我在下面复制粘贴该实现,但所有的配额都归Jodrell所有。

代码语言:javascript
复制
public static IEnumerable<T> Shuffle<T>(
        this IEnumerable<T> source,
        Random generator = null)
{
    if (generator == null)
    {
        generator = new Random();
    }

    var elements = source.ToArray();
    for (var i = elements.Length - 1; i >= 0; i--)
    {
        var swapIndex = generator.Next(i + 1);
        yield return elements[swapIndex];
        elements[swapIndex] = elements[i];
    }
}

然后,您可以使用以下命令:

代码语言:javascript
复制
hidingSpot = hidingSpot.Shuffle().ToArray();
string one = hidingspot[0];
string two = hidingspot[1];
string three = hidingspot[2];
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35459528

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档