Parsing a 1-mutable-register instruction set?

Brief Description of the Problem

I need to be able to generate instructions for a conceptual set of CPU + instructions. I have an almost working algorithm.

The CPU has only 1 mutable register (named mut), which always starts as 1, and a certain number of immutable registers with values ​​in them (named input [0..n]). The instructions for this CPU are just a logical gate on a mut with one of the input registers that save the result back to mut.

I need an algorithm to generate instructions that will allow this CPU to generate the correct answer for every possible set of inputs from some specific truth table.

Example

As an example, perhaps I want this processor to work as an AND logic element (which has a truth table 00=0,01=0,10=0,11=1). I should be able to feed the algorithm of this truth table and call the instructions " AND[0] AND[1]". If you follow your head, you will see that MUT will remain only 1 if both INPUT [0] and INPUT [1] are 1.

Attempt

, , / , , . , . , , , .

- , ) , c) ?

, 2D- , , , 1D- .

, , . , .

, :

AND[n]: MUT = MUT & INPUT[n]
OR[n]: MUT = MUT | INPUT[n]
NOT: MUT = ~MUT

CPU, .

+4
1

, , . , , , . XOR.

, ACC ( False) ACC, :

ACC <- ACC or MUT
MUT <- True

, rules, bools, , 0..n . , XOR [[True, True, True], [False, False, True], [False, True, False], [True, False, False]].

, , :

def generateCode (rules):
    rules = [rule for rule in rules if rule [0] ]
    if not rules: return []
    opcodes = []
    for rule in rules:
        rule = rule [1:]
        negs = [i for i, e in enumerate (rule) if not e]
        poss = [i for i, e in enumerate (rule) if e]
        if negs:
            opcodes.append ('NOT')
            for neg in negs: opcodes.append ('OR[{}]'.format (neg) )
            opcodes.append ('NOT')
        if poss:
            for pos in poss: opcodes.append ('AND[{}]'.format (pos) )
        opcodes.append ('ACC')
    return opcodes

, , ['AND[0]', 'AND[1]', 'ACC', 'NOT', 'OR[0]', 'OR[1]', 'NOT', 'ACC'], .

, . reset, ACC .

class CPU:
    def reset (self, inputs):
        self.MUT = True
        self.ACC = False
        self.INP = inputs [:]

    def __call__ (self, opcodes):
        for opcode in opcodes:
            if opcode == 'NOT':
                self.MUT = not self.MUT
                continue
            if opcode == 'ACC':
                self.ACC = self.ACC or self.MUT
                self.MUT = True
                continue
            if opcode [0] == 'O':
                inp = int (opcode [3:-1] )
                self.MUT = self.MUT or self.INP [inp]
                continue
            if opcode [0] == 'A':
                inp = int (opcode [4:-1] )
                self.MUT = self.MUT and self.INP [inp]
                continue
            raise Exception ('Need more dried frog pills.')
        return self.ACC

, , , , , , .

+2

All Articles