如何从char数组中选择随机元素并将其分配给列表 [英] How to select random element from char array and assign it to list

查看:96
本文介绍了如何从char数组中选择随机元素并将其分配给列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个char数组(A)和一个int数组(B)。我想从数组A中随机选择元素(所选元素必须是唯一的),并将它们与来自第一个元素的数组B的元素连接起来。将连接元素添加到字符串列表。

我的问题是所选元素不是唯一的。



我有什么试过:



I have a char array(A) and int array(B). I want to select elements randomly from array A(selected elements have to be unique) and concatenate them with elements of array B from first element. Add the concatenated elements to a string list.
My problem is that selected elements aren't unique.

What I have tried:

List<string> AB_Concat = new List<string>();
Random random = new Random();
for(int i=0;i<26;i++)
    AB_Concat.Add(Convert.ToString(A[random.Next(i, A.Length)]) + Convert.ToString(B[i]));

for (int i = 0; i < 26; i++)
   Console.Write(AB_Concat[i] + " ");

推荐答案

如果您需要阵列A中的唯一字符 - 即它类似于一包卡片,您只能拥有其中一个 - 那么您在使用时需要从输入中删除每个字符它。

最简单的方法是将数组转换为List并每次使用RemoveAt:

If you need unique characters from Array A - i.e. it's similar to a pack of cards, you can only have one of each - then you need to remove each character from the input when you use it.
The simplest way to do that is to convert your array to a List and use RemoveAt each time:
List<string> AB_Concat = new List<string>();
List<char> data = A.ToList();
Random random = new Random();
for (int i = 0; i < 26; i++)
    {
    int index = random.Next(data.Count);
    AB_Concat.Add(Convert.ToString(data[index]) + Convert.ToString(B[i]));
    data.RemoveAt(index);
    }
for (int i = 0; i < 26; i++)
    {
    Console.Write(AB_Concat[i] + " ");
    }


您需要使用不允许重复的集合,例如 HashSet(T)类(System.Collections.Generic) [ ^ ]。然后,您还需要添加代码以继续添加,直到该集合包含26个项目,而不是仅仅迭代您的列表26次。
You need to use a collection that does not allow duplicates, such as the HashSet(T) Class (System.Collections.Generic)[^]. You will also then nedd to add code to keep adding until the set contains 26 items, rather than just iterating your list 26 times.


这篇关于如何从char数组中选择随机元素并将其分配给列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆