// Arup Guha
// 12/5/2023
// Solution to Q12 of COP 3502 Section 4 Part B Exam

#include <stdio.h>
#include <stdlib.h>
int getcommonlang(int** languages, int n, int m);

int main() {

    // Set up a test grid.
    int** grid = calloc(5, sizeof(int*));
    for (int i=0;i<5; i++) grid[i] = calloc(4, sizeof(int));

    // Fill it.
    grid[0][0] = 13; grid[0][1] = 32; grid[0][2] = 77; grid[0][3] = 24;
    grid[1][0] = 3; grid[1][1] = 11; grid[1][2] = 18; grid[1][3] = 75;
    grid[2][0] = 80; grid[2][1] = 9; grid[2][2] = 0; grid[2][3] = 0;
    grid[3][0] = 80; grid[3][1] = 9; grid[3][2] = 0; grid[3][3] = 0;
    grid[4][0] = 0; grid[4][1] = 65; grid[4][2] = 72; grid[4][3] = 38;

    // Run it.
    printf("%d\n", getcommonlang(grid, 5,4));

    // Free stuff.
    for (int i=0; i<5; i++)
        free(grid[i]);
    free(grid);

    return 0;
}

int getcommonlang(int** languages, int n, int m) {

    // Initialize to all languages.
    int res = (1<<20)-1;

    // Go through each team.
    for (int i=0; i<n; i++) {

        // See the coverage of this team, use or.
        int cover = 0;
        for (int j=0; j<m; j++)
            cover |= languages[i][j];

        // We use and because our answer is limited by what this team knows
        res &= cover;
    }

    return res;
}
