I have an 2d array with chars 6×6 and looks something like this and Im trying to create an method witch needs to replace duplicates in row with ‘@’ character
a b a a
a a b c
a a a b
a a a a
and after replacing with method should look like this
a b @ @
a @ b c
a @ @ b
a @ @ @
I have tried this method but no results "I need to make this work without libraries"
public void RemoveDuplicates(char[,] array)
{
char symbol = '@';
for (int i = 0; i < array.GetLength(0); i++)
{
for (int j = 0; j < array.GetLength(1); j++)
{
int temp = array[i, j];
int next = ++temp;
if(temp == next)
{
next = symbol;
}
}
}
}
3
Answers
You can use Hashset (or list also) collection (docs: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/collections) to store your duplicates as follows:
Or list as follows:
The goal should be to keep track of all previously seen characters. So you need some kind of ‘set’ data structure for this. The easy way would be to use an HashSet. This has an add method that adds the value to the set, and return false if the value was already in the set.
HashSet is part of the framework, so would not normally be considered a "library".
If that is now allowed you could provide similar functionality with an plain array.
But I would probably not recommend such a solution since it uses much more memory compared to the hashSet.
Probably not the fastest solution but pretty simple to understand
Considering this input
With this code it will take each row, one by one, then replace duplicated values
Result:
PS: You can improve a bit the code by iterating "data.GetLength(1) -1" as the last cell cant have a duplicate.
And skip the loop if the value of the cell is ‘@’, in the current code you will replace some ‘@’ by another ‘@’ 😀