-1

I am having trouble finding the number of distinct elements in a 2D-array using for loops. I know how to do it if its a 1D-array but can't seem to figure out how to do it for 2D-array.

I tried searching for it, but can't seem to quite understand how some of the example works.

New Pea
  • 141
  • 1
  • 8
  • Consider you 2D array as 1D array, and resolve your problem ? – Jarod42 Jan 26 '19 at 01:39
  • @Jarod42 I can solve the problem if its a 1D array, but i can't visualize how i am suppose to connect the Row Array and Column Array if i separate the 2. – New Pea Jan 26 '19 at 01:42
  • 2
    You can make a 1D array look like a 2D array by using `row * number_of_columns + column` as the index. As a side benefit, often this leads to a faster program if you have to dynamically allocate a 2D array. You only have one (big) allocation instead of many and all of the elements are packed into one contiguous block rather than in many blocks potentially scattered throughout memory. – user4581301 Jan 26 '19 at 01:46
  • Didn't explain why that's helpful. Since you have a 1D array, you can now use your 1d array algorithm on it while allowing the rest of the program to interact with the array in 2 dimensions. – user4581301 Jan 26 '19 at 01:48
  • @user4581301 So i assume i'm suppose to make my 2D array look like a 1D array? The way i can think of now is to pass my values from a 2D array into a 1D array and use the 1D array algorithm – New Pea Jan 26 '19 at 02:14
  • I assume you can iterate over 2d array. If the numbers in the array are non-negative and are in short definite range for ex : bewtween 0 to 10^6 then you can use a 1d array to store the frequency of each number. If this isn't the case, you can use unorderd_set and print the size of set – Brij Raj Kishore Jan 26 '19 at 02:14
  • https://www.geeksforgeeks.org/multidimensional-arrays-c-cpp/, Not exactly c++, it is actually c but it will work in case of c++ https://overiq.com/c-programming-101/pointers-and-2-d-arrays/ – Brij Raj Kishore Jan 26 '19 at 02:19
  • Here is a good example of someone who has taken a 1D array and wrapped it up in a class so it looks like a 2D array: https://stackoverflow.com/a/2076668/4581301 – user4581301 Jan 26 '19 at 02:20
  • Check the answer i think it will work for you . – Hamza.S Jan 26 '19 at 17:10

1 Answers1

0

I recommend you to use std::array and use the find() method for finding specific element in the array.

int array[5][4] = {{ 34,  56, 79, 12}, 
                        { 25, 37, 41, 18  },
                        { 59, 29,  38, 47 },
                        { 55,  11, 88, 34 },
                        { 45, 19,  34, 66 } };

And use

find(array[0], array[n-1]+m, x)

//array is your 2D array, n is the first dimension, m is the second and x is your value
Hamza.S
  • 1,319
  • 9
  • 18