c# - 洗牌字符串数组没有重复

标签 c# .net-4.0

我正在使用 Knuth-Fisher-Yates 算法在 Windows 窗体上显示打乱的字符串项数组。我没有得到任何重复项,这是我试图实现的,但是,它只吐出数组 13 个元素中的 12 个。我怎样才能让它显示数组的所有 13 个元素?这是我的代码:

private void FormBlue1_Load(object sender, EventArgs e)
{
// set the forms borderstyle
this.FormBorderStyle = FormBorderStyle.Fixed3D;

// create array of stationOneParts to display on form
string[] stationOneParts = new string[13];
stationOneParts[0] = "20-packing";
stationOneParts[1] = "5269-stempad";
stationOneParts[2] = "5112-freeze plug";
stationOneParts[3] = "2644-o'ring";
stationOneParts[4] = "5347-stem";
stationOneParts[5] = "4350-top packing";
stationOneParts[6] = "5084-3n1 body";
stationOneParts[7] = "4472-packing washer";
stationOneParts[8] = "3744-vr valve o'ring";
stationOneParts[9] = "2061-packing spring";
stationOneParts[10] = "2037-packing nut";
stationOneParts[11] = "2015-latch ring";
stationOneParts[12] = "stem assembly";

Random parts = new Random();

// loop through stationOneParts using a Swap method to shuffle
labelBlueOne.Text = "\n";
for (int i = stationOneParts.Length - 1; i > 0; i--)
{
int j = parts.Next(i + 1);
Swap(ref stationOneParts[i], ref stationOneParts[j]);

// display in a random order
labelBlueOne.Text += stationOneParts[i] + "\n";
}
}

private void Swap(ref string firstElement, ref string secondElement)
{
string temp = firstElement;
firstElement = secondElement;
secondElement = temp;
}

最佳答案

您不访问第一个元素。 for (int i = stationOneParts.Length - 1; i >= 0; i--).

关于c# - 洗牌字符串数组没有重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6188331/

相关文章:

c# - 我可以阻止 .net 4.0 对单引号进行编码吗?

wcf - "Fast"WCF服务的集成测试

c# - 如何在退出 WPF 应用程序时禁用清除剪贴板?

c# - 列表在调试时不填充,直到打开

javascript - 如何在 Controller 中保留 html 中的变量?

c# - 重写if语句: One of these statements ended up with one too many pair of braces

c# - 如何在 Visual Studio 2010 中将自己的扩展添加到 html/aspx 代码编辑器的上下文菜单中?

c# - 从我的项目文件创建新的 docker 镜像时出错

c# - .Net Core Swashbuckle 在重定向时跳过授权 header

由于猴子补丁的能力,.NET 4 可以实现更好的单元测试/模拟?