# Thread: Finding an array of unique values within a 2D array

1. ## Finding an array of unique values within a 2D array

Hi! I am new to C programming. I am trying to write a program that involves finding unique values in a 2D array and saving them in a separate array. The values in the 2D array are not sorted. Also, a value and its negative should be considered the same. For example, if the 2D array is
Code:
```int array[][] = {1, 2, 3}
{-3, 4, 1}
{-1, 2, 5}
{5, 2, 6}
//The array of the unique values should be
unique[] = {1, 2, 3, 4, 5, 6}```
Please explain the code that would carry out this function. Thank you!

2. An simple insertion sort using absolute values would solve the problem.

Tim S.
PS: No code supplied by me.

3. Thanks for the reply. However, what I wanted to ask was that how can I move through the 2D array and select the unique values. I have to ensure that the values are not similar to those encountered previously before I can add them to the 1D array of unique values. Moreover, if a value is negative and its positive is not an element in a 2D array, it should go in the unique array as positive.

4. Well... what have you tried so far?

You could use for loops to iterate the elements of the array. A for loop will work to check it against the elements of your unique[] array. Try to figure it out and implement something then if you have a specific question or get stuck, come back and ask about that.

5. Out of curiosity, but suppose this was a 1D instead of 2D array. Would you know how to solve the problem then?

6. I have tried solving the problem using for loops as shown below. I get a segmentation fault. The code is given below. The x[] is the array of unique elements (size of x[] is n+1) and I have already assigned values to its first two elements as can be seen. The cn[][] is the 2D array (size [c][3]). Since I am new to C programming, I am not that good as using nested for loops. Please correct the error in the code.
Code:
```int x[n+1];
x[0] = 0;
x[1] = cn[0][0];
int i, j, k, l;
for(k = 2; k < n+1; )
for(i = 0; i < c; i++)
for(j = 0; j < 3; j++)
for(l = 1; l < k; l++)
if(x[l] != cn[i][j])
{
x[k] = cn[i][j];
k++;
}```

7. Imagine that your unique array was full of zero's to start. Now your function could "walk" through the number array, and every value it found, it could add 1 to the unique array INDEX element. If you found a 4 then unique[4] = unique[4]+1. (C has a more concise way of representing an increment, find it).

When you have "walked" through every value in the number array, your unique[] will have a story to tell you. Print it out and study it. Read up on "Counting Sort", which uses this principle very well.

Your other code is working WAY too hard. This is beautifully simple.

Popular pages Recent additions