Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,872 questions

51,796 answers

573 users

How to flatten a 2D array into a sorted one-dimensional array with unique values in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>

#define ROWS 3
#define COLS 4
#define SIZE ROWS * COLS

int RemoveDuplicates(int arr[], int size) {
    for (int i = 0; i < size; i++) {
        for (int j = i + 1; j < size; j++) {
            if (arr[i] == arr[j]) {
                // Delete the current duplicate element 
                for (int k = j; k < size - 1; k++) {
                    arr[k] = arr[k + 1];
                }
                size--;
                j--; // don't increment
            }
        }
    }
      
    return size;
}

int compare(const void *a, const void *b) {
    return (*(int*)a - *(int*)b);
}

void Flatten2DArrayIntoSorted1DArray(int array2d[][COLS], int rows, int cols, int arr[]) {
    int index = 0;

    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            if (array2d[i][j] != 0) {
                arr[index++] = array2d[i][j];
            }
        }
    }

    qsort(arr, index, sizeof(int), compare);
}


int main() {
    int array2d[][COLS] = {
        {4, 5, 9, 3},
        {1, 4, 5, 1},
        {7, 5, 6, 8},
    };
    
    int arr[SIZE];
    
    Flatten2DArrayIntoSorted1DArray(array2d, ROWS, COLS, arr);

    int size = RemoveDuplicates(arr, SIZE);
      
    for (int i = 0; i < size; i++) {
        printf("%d, ", arr[i]);
    }

    return 0;
}


/*
run:

1, 3, 4, 5, 6, 7, 8, 9, 

*/

 



answered Aug 15, 2024 by avibootz
...