Distinct values in 2D char array...
-
Hello! We have 2D array, Data[20][10], it contains some values, want some suggestions on how to count the distinct values in the array, without getting into 19 loops from 0 to 19 checking against each value!!! We are using VC++ 6. Thanks Adeel --
-
Hello! We have 2D array, Data[20][10], it contains some values, want some suggestions on how to count the distinct values in the array, without getting into 19 loops from 0 to 19 checking against each value!!! We are using VC++ 6. Thanks Adeel --
What is the range of your values? If it's not a huge range (more than 0-1000000), you can use a bucket sort technique, which is to basically initialize an array of bools of size 1000000, and set all initial values to false (I'm not sure what values they default to). Then, iterate through all the data in your 2D array and for each value, check if the bool array entry corresponding to the value is true. If it is, then you know you have duplicate values. If it's false, then set the bool array entry to true, so next time, it will detect a duplicate value. Example: If the current iteration of your 2D array gives you a value of 5, you set boolArray[5] = true. If you wish to count the values, then you can use an int array instead of a bool array and just increment as you go.
-
Hello! We have 2D array, Data[20][10], it contains some values, want some suggestions on how to count the distinct values in the array, without getting into 19 loops from 0 to 19 checking against each value!!! We are using VC++ 6. Thanks Adeel --
madeelch1986 wrote:
We have 2D array, Data[20][10], it contains some values, want some suggestions on how to count the distinct values in the array
Stealing from Cyrilix, here's one way...
char Data[20][10];
// ... initialize Data[][] here ...
bool Flags[256];
memset(Flags, 0, sizeof(Flags));
int UniqueCount = 0;
for (int i = 0; i < 20; i++)
{
for (int j = 0; j < 10; j++)
{
if (false == Flags[(unsigned char)Data[i][j]])
{
Flags[(unsigned char)Data[i][j]] = true;
++UniqueCount;
}
}
}"Posting a VB.NET question in the C++ forum will end in tears." Chris Maunder