In this HackerEarth Binary associativity problem solution, A binary operation * on a set S is called associative if it satisfies the associative law: (x * y) * z = x * (y * z) for all x, y, z in S.

For the binary set S = {0,1} and a particular binary operator *, you are given its truth table. Determine if the operation is associative.


HackerEarth Binary associativity problem solution


HackerEarth Binary associativity problem solution.

#include <bits/stdc++.h>
using namespace std;

int F[4];

int func(int a, int b)
{
  if(a == 0 && b == 0)
    return F[0];
  else if(a == 0 && b == 1)
    return F[1];
  else if(a == 1 && b == 0)
    return F[2];
  else
    return F[3];
}

bool isGood(int a, int b, int c)
{
  return func(func(a, b), c) == func(a, func(b, c));
}

int main()
{
  int T;
  cin >> T;
  
  while(T--)
  {
    for(int i=0; i<4; i++)
      cin >> F[i];
    
    bool is_associative = true;
    
    for(int a=0; a<=1; a++)
      for(int b=0; b<=1; b++)
        for(int c=0; c<=1; c++)
          is_associative &= isGood(a, b, c);
    
    if(is_associative)
      cout << "Yes\n";
    else
      cout << "No\n";
  }
  
  return 0;
}


Second solution

#include <bits/stdc++.h>

using namespace std;

int main(int argc, char* argv[]) {
    if(argc == 2 or argc == 3) freopen(argv[1], "r", stdin);
    if(argc == 3) freopen(argv[2], "w", stdout);
    int t, c[2][2], x1, x2, x;
    bool flag;
    assert(cin >> t);
    assert(1 <= t and t <= 8);
    for(int test = 0; test < t; test++) {
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                assert(cin >> c[i][j]);
                assert(0 <= c[i][j] and c[i][j] <= 1);
            }
        }
        flag = true;
        for(int i = 0; i < 2; i++) {
            for(int j = 0; j < 2; j++) {
                for(int k = 0; k < 2; k++) {
                    x = c[k][j];
                    x1 = c[x][i];
                    x = c[j][i];
                    x2 = c[k][x];
                    if (x1 != x2) flag = false;
                }
            }
        }
        cout << (flag ? "Yes" : "No") << endl;
    }
    assert(!(cin >> t));
    return 0;
}