Convert the python program to C++ (preferably C++ in Eclipse) from itertools imp
ID: 3735845 • Letter: C
Question
Convert the python program to C++ (preferably C++ in Eclipse)
from itertools import *
# Logic functions: take and return iterators of truth values
def AND(a, b):
for p, q in zip(a, b):
yield p and q
def OR(a, b):
for p, q in zip(a, b):
yield p or q
def NOT(a):
for p in a:
yield not p
def EQUIV(a, b):
for p, q in zip(a, b):
yield p is q
def IMPLIES(a, b):
for p, q in zip(a, b):
yield (not p) or q
def create(num=2):
''' Returns a list of all of the possible combinations of truth for the given number of variables.
ex. [(T, T), (T, F), (F, T), (F, F)] for two variables '''
return list(product([True, False], repeat=num))
def unpack(data):
''' Regroups the list returned by create() by variable, making it suitable for use in the logic functions.
ex. [(T, T, F, F), (T, F, T, F)] for two variables '''
return [[elem[i] for elem in lst] for i, lst in enumerate(tee(data, len(data[0])))]
def print_result(data, result):
''' Prints the combinations returned by create() and the results returned by the logic functions in a nice format. '''
n = len(data[0])
headers = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:n]
print (headers + "|RESULT")
print ('-' * len(headers) + '+------')
for row, result_cell in zip(data, result):
print (''.join({True: 'T', False:'F'}[cell] for cell in row) + '|' + ' ' + {True: 'T', False:'F'}[result_cell])
if __name__ == '__main__':
data = create(num=3)
A, B, C = unpack(data)
result = AND(A, OR(B, C))
print_result(data, result)
Explanation / Answer
#include <iostream>
#include <cmath>
#include <string.h>
using namespace std;
int length_row, length_col;
int* AND(int a[], int b[]) {
int* res = new int[length_row];
for(int i=0; i<length_row; i++) {
res[i] = (a[i] & b[i]);
}
return res;
}
int* OR(int a[], int b[]) {
int* res = new int[length_row];
for(int i=0; i<length_row; i++) {
res[i] = (a[i] | b[i]);
}
return res;
}
int* NOT(int a[]) {
int* res = new int[length_row];
for(int i=0; i<length_row; i++) {
cout << a[i];
res[i] = (a[i] == 0 ? 1 : 0);
}
return res;
}
int** create(int num=2) {
int row = pow(2, num);
length_row = row;
length_col = num;
int** arrayData = new int*[row];
for (int h = 0; h < row; h++) {
arrayData[h] = new int[num];
int k=0;
for (int j=num-1; j>=0; j--) {
arrayData[h][k] = ((h/(int) pow(2, j))%2 == 0);
k++;
}
}
return arrayData;
}
void print_result(int** data, int result[]) {
string headers = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
cout << endl << headers.substr(0, length_col) << "|RESULT";
for(int i=0 ; i<length_row; i++) {
cout << endl;
for(int j=0 ; j<length_col; j++) {
cout << (data[i][j] == 1 ? 'T' : 'F');
}
cout << " " << (result[i] == 1 ? 'T' : 'F');
}
}
int main()
{
int** arrayData = create(3);
int* result = AND(arrayData[0], OR(arrayData[1], arrayData[2]));
print_result(arrayData, result);
return 0;
}
** OUTPUT **
ABC|RESULT
TTT T
TTF T
TFT T
TFF F
FTT F
FTF F
FFT F
FFF F