Click here to Skip to main content
15,887,338 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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:

C#
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] + " ");
Posted
Updated 3-Nov-16 7:49am
v2
Comments
Patrice T 3-Nov-16 13:43pm    
And you have a question ? or a problem ?

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:
C#
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] + " ");
    }
 
Share this answer
 
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900