Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #define MAXINPUT 10
- typedef enum {IN0 = 0, IN1 = 1, ANDG, ORG, XORG, NANDG, NORG, INVG} GateType;
- typedef struct Gate* GatePtr;
- struct Gate {
- GateType type;
- GatePtr input1;
- GatePtr input2;
- GatePtr input3;
- GatePtr input4;
- };
- int initialiseInputArray (GatePtr gateArray[], int count)
- {
- int i = 0;
- while (i < count) {
- GatePtr g = malloc(sizeof(struct Gate));
- g->input1 = NULL;
- g->input2 = NULL;
- g->type = IN0;
- gateArray[i] = g;
- ++i;
- }
- gateArray[i] = NULL;
- }
- int resetInput (GatePtr gateArray[])
- {
- /* Must set all inputgates to type IN0 */
- GatePtr g = *gateArray;
- while (g != NULL) {
- g->type = IN0;
- g = *(++gateArray);
- }
- }
- int applyNextInput (GatePtr gateArray[])
- {
- GatePtr g = *gateArray;
- int done = 0;
- int overflow = 1;
- while (!done) {
- if (g->type == IN0) {
- // Add one and return
- g->type = IN1;
- done = 1;
- overflow = 0;
- }
- else {
- // Reset and carry:
- g->type = IN0;
- g = *(++gateArray);
- }
- if (g == NULL)
- done = 1;
- }
- return overflow;
- }
- int eval(GatePtr gate) {
- if(gate->type == IN0) {
- return 0;
- } else if(gate->type == IN1) {
- return 1;
- } else if(gate->type == ANDG) {
- return eval(gate->input1) & eval(gate->input2)
- & eval(gate->input3)& eval(gate->input4);
- } else if (gate->type == ORG) {
- return eval(gate->input1) | eval(gate->input2);
- } else if(gate->type == XORG) {
- return eval(gate->input1) ^ eval(gate->input2);
- } else if (gate->type == NANDG) {
- return !(eval(gate->input1) & eval(gate->input2));
- } else if (gate->type == NORG) {
- return !(eval(gate->input1) | eval(gate->input2));
- } else if (gate->type == INVG) {
- return !(eval(gate->input1));
- }
- }
- void printTruthTable(GatePtr inputGates[], int results[]) {
- GatePtr gate = *inputGates;
- while (gate != NULL) {
- if(gate->type == IN0) {
- printf("|\t0\t|");
- } else if (gate->type == IN1) {
- printf("|\t1\t|");
- }
- gate = *(++inputGates);
- }
- int * result = results;
- while(*result != -1) {
- printf("|\t%d\t|", *result);
- result = ++results;
- }
- printf("\n");
- }
- int main(void) {
- GatePtr inputGates[MAXINPUT+1];
- initialiseInputArray (inputGates, 4);
- GatePtr andgate = malloc(sizeof(struct Gate));
- andgate->type = ANDG;
- andgate->input1 = inputGates[0];
- andgate->input2 = inputGates[1];
- andgate->input3 = inputGates[2];
- andgate->input4 = inputGates[3];
- resetInput(inputGates);
- do {
- int out = eval(andgate);
- int results[4] = {out, -1};
- printTruthTable(inputGates, results);
- } while (!applyNextInput(inputGates));
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement