Skip to content

Commit

Permalink
Enable inverted iterators.
Browse files Browse the repository at this point in the history
  • Loading branch information
tristanmorgan committed Jul 31, 2024
1 parent b1d600a commit f37b8ce
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 30 deletions.
5 changes: 0 additions & 5 deletions parser/instruction.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,6 @@ func (inst Instruction) SameOp(instTwo Instruction) bool {
return inst.operator == instTwo.operator
}

// Complement compares Instructions operator and operand
func (inst Instruction) Complement(instTwo Instruction) bool {
return inst.SameOp(instTwo) && inst.operand+instTwo.operand == 0
}

// IsZeroOp returns true for ops that have left the pointer on a zero
func (inst Instruction) IsZeroOp() bool {
return !(inst.operator == opAddDp ||
Expand Down
23 changes: 0 additions & 23 deletions parser/instruction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,26 +140,3 @@ func TestSameOp(t *testing.T) {
}

}

func TestComplement(t *testing.T) {
opsList := []Opcode{
opAddDp,
opAddVal,
}

for row, rval := range opsList {
for col, cval := range opsList {
t.Run(fmt.Sprintf("%s-%s", opName[rval], opName[cval]), func(t *testing.T) {
for operand := range [6]int{} {
rinst := Instruction{rval, operand}
cinst := Instruction{cval, operand - 6}
want := row == col && operand == 3

if rinst.Complement(cinst) != want {
t.Errorf("testing %v vs %v want %v", rinst, cinst, want)
}
}
})
}
}
}
11 changes: 9 additions & 2 deletions parser/tokenise.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,14 +111,16 @@ func Tokenise(input io.ByteReader) (program []Instruction, err error) {

func evalFactors(program []Instruction) (pointers, factors []int, ok bool) {
ok = false
invert := false
collect := 0
pointers = make([]int, 0)
factors = make([]int, 0)
for _, inst := range program {
if inst.SameOp(NewInstruction('>')) {
collect += inst.operand
} else if collect == 0 && inst.Complement(NewInstruction('+')) {
ok = true
} else if collect == 0 && inst.SameOp(NewInstruction('-')) {
ok = inst.operand == 1 || inst.operand == -1
invert = inst.operand == 1
} else if inst.SameOp(NewInstruction('-')) {
pointers = append(pointers, collect)
factors = append(factors, inst.operand)
Expand All @@ -129,5 +131,10 @@ func evalFactors(program []Instruction) (pointers, factors []int, ok bool) {
if collect != 0 || !ok {
return pointers, factors, false
}
if invert {
for i := range len(factors) {
factors[i] = 0 - factors[i]
}
}
return
}

0 comments on commit f37b8ce

Please sign in to comment.