Forums: » Register « |  Free Tools |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support |

New Free Tools on Dev Shed!

#1
November 14th, 2011, 09:41 PM
 new2C
Registered User

Join Date: Nov 2011
Posts: 2
Time spent in forums: 18 m 45 sec
Reputation Power: 0
Finding unique values in 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

{1,2,3}
{-3,4,1}
{-1,2,5}
{5,2,6}

Then the array of unique values should be {1,2,3,4,5,6}

I would like to solve the problem using nested for loops but any kind of help would be appreciated. Thank You!

#2
November 14th, 2011, 10:39 PM
 kicken
Wiser? Not exactly.

Join Date: May 2001
Location: Bonita Springs, FL
Posts: 5,789
Time spent in forums: 2 Months 2 Weeks 4 Days 2 h 49 m 37 sec
Reputation Power: 3716
Create your third unique values array, initially empty. As you loop through your 2d array set, check if the current value exists in the unique array. If it does not yet exist, then add it before moving to the next loop. If it does exist, skip it and move on.
__________________
Recycle your old CD's, don't just trash them

If I helped out out, show some love with some reputation, or tip with Bitcoins to 1N645HfYf63UbcvxajLKiSKpYHAq2Zxud

#3
November 14th, 2011, 11:38 PM
 new2C
Registered User

Join Date: Nov 2011
Posts: 2
Time spent in forums: 18 m 45 sec
Reputation Power: 0
Why do I need to create a third array? The unique array itself initially has no values. It has to be filled by walking through the 2D array and collecting the unique values. I tried using nested for loops but my code doesn't work. Can you please explain the code that walks through the 2D array and adds the unique values to unique array which is 1D and initially empty.

#4
November 15th, 2011, 01:22 AM
 kicken
Wiser? Not exactly.

Join Date: May 2001
Location: Bonita Springs, FL
Posts: 5,789
Time spent in forums: 2 Months 2 Weeks 4 Days 2 h 49 m 37 sec
Reputation Power: 3716
Quote:
 Originally Posted by new2C Why do I need to create a third array? The unique array itself initially has no values.

The third array is the unique array. Probably talking about the same thing. I counted the 2D array as two arrays, but I guess it could be counted as one, in which case the unique array is your second array.

As for the loop, in pseudo code:
Code:
```int uniqLen=0;
int x=0;
int y=0;

for (; x<len_of_d1; x++){
for (; y<len_of_d2; y++){
if (!in_array(2darr[x][y], uniqArr)){
uniqArr[uniqLen++] = 2darr[x][y];
}
}
}```

 Viewing: Dev Shed Forums > Programming Languages > C Programming > Finding unique values in a 2D array