Traversing through a 2D array?

I have a 2D array of ints and I want to check that within this array, only one value of each number 1 through N exist (for example, N being 9, that only 1-9 exist once and only once). I was thinking of approaching this by using some sort of loop and testing each element value against the loop counter. Anyone got some suggestions?
Not sure what you're going after here. The whole array can only have once instance of a specific number? I'll recommend using a 1D array, you can use them the same way as a 2D array, and it's much easier to work with
well I have something like this:

[1][2][3]
[4][5][6]
[7][8][9]

and I want to ensure that there's only one occurrence of each value 1-9.
I'm assuming you want it sorted it too? I'd do the sorting first, and then replace the duplicates with whatever number it should be.
simple, yet i am unsure if it is the most efficient. use 2 pointers.

one pointer looks at a certain location

array[0][0]

the second pointer looks at a different location then compares

array[1][0]

you can use a loop as u said to increment either location.

array[loopVar1] [loopVar2]
Off the top of my head, I came up with the following code. It needs some tweaking, so that the loop skips a future location, if it has had a match before.

There's probably a better/cleaner way to do it, but here it is:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
#include <iostream>		// cout


int main()
{
	int ary[ 3 ][ 3 ] = { { 1, 2, 7 },
			      { 3, 5, 9 },
			      { 4, 6, 5 } };

	// print the array
	for( int i = 0; i < 3; ++i )
	{
		for( int j = 0; j < 3; ++j )
			std::cout << ary[ i ][ j ] << ' ';

		std::cout << '\n';
	}

	// location_i & location_j will stay the same until the iner loop
	// has traversed through the whole array once.
	for( int location_i = 0; location_i < 3; ++location_i )
	{
		for( int location_j = 0; location_j < 3; ++location_j )
		{

			// loop which will check against the location element
			for( int check_i = 0; check_i < 3; ++check_i )
			{
				for( int check_j = 0; check_j < 3; ++check_j )
				{
					// if the location and check are at the same element
					// the number will be the same, so skip it( continue; )
					if( ( location_i == check_i ) && ( location_j == check_j ) )
						continue;

					// if the check matches the location
					if( ary[ location_i ][ location_j ] == ary[ check_i ][ check_j ] )
					{
						std::cout << "Match at: " << location_i << ' ' << location_j;
						std::cout << "\nNumber was: " << ary[ location_i ][ location_j ] << '\n';
					}
				}
			}
		}
	}
    
    return 0;
}
Last edited on
Topic archived. No new replies allowed.