|
| 1 | +import subprocess |
| 2 | + |
| 3 | +from vim_turing_machine.machines.merge_overlapping_intervals.decode_intervals import decode_intervals |
| 4 | +from vim_turing_machine.machines.merge_overlapping_intervals.encode_intervals import encode_intervals |
| 5 | +from vim_turing_machine.machines.merge_overlapping_intervals.merge_overlapping_intervals import MergeOverlappingIntervalsGenerator |
| 6 | +from vim_turing_machine.vim_constants import VIM_MACHINE_FILENAME |
| 7 | +from vim_turing_machine.vim_machine import VimTuringMachine |
| 8 | + |
| 9 | + |
| 10 | +NUM_BITS = 3 |
| 11 | + |
| 12 | + |
| 13 | +def run_vim_machine(intervals): |
| 14 | + initial_tape = encode_intervals(intervals, NUM_BITS) |
| 15 | + |
| 16 | + gen = MergeOverlappingIntervalsGenerator(NUM_BITS) |
| 17 | + merge_overlapping_intervals = VimTuringMachine(gen.merge_overlapping_intervals_transitions(), debug=False) |
| 18 | + |
| 19 | + # Write to the vim machine file |
| 20 | + merge_overlapping_intervals.run(initial_tape=initial_tape) |
| 21 | + |
| 22 | + subprocess.run( |
| 23 | + [ |
| 24 | + 'vim', |
| 25 | + '-u', |
| 26 | + 'vimrc', |
| 27 | + VIM_MACHINE_FILENAME, |
| 28 | + '-c', |
| 29 | + # Execute the vim machine and then save the resulting file |
| 30 | + ":execute 'normal gg0yy@\"' | :x", |
| 31 | + ], |
| 32 | + timeout=10, |
| 33 | + check=True, |
| 34 | + ) |
| 35 | + |
| 36 | + |
| 37 | +def read_contents_of_tape(): |
| 38 | + with open(VIM_MACHINE_FILENAME, 'r') as f: |
| 39 | + tape_lines = [] |
| 40 | + found_beginning_of_tape = False |
| 41 | + |
| 42 | + for line in f: |
| 43 | + # Look for the lines between '_t:' and 'notvalid' |
| 44 | + if line.startswith('_t:'): |
| 45 | + found_beginning_of_tape = True |
| 46 | + elif line.startswith('notvalid'): |
| 47 | + return convert_tape_to_string(tape_lines) |
| 48 | + elif found_beginning_of_tape: |
| 49 | + tape_lines.append(line) |
| 50 | + |
| 51 | + raise AssertionError('Could not find the tape') |
| 52 | + |
| 53 | + |
| 54 | +def convert_tape_to_string(tape_lines): |
| 55 | + return ''.join(tape_lines).replace(' ', '').replace('\n', '') |
| 56 | + |
| 57 | + |
| 58 | +def test_merge_intervals_in_vim(): |
| 59 | + run_vim_machine([[1, 2], [2, 3], [5, 7]]) |
| 60 | + tape = read_contents_of_tape() |
| 61 | + |
| 62 | + intervals = decode_intervals(tape, num_bits=NUM_BITS) |
| 63 | + assert intervals == [[1, 3], [5, 7]] |
0 commit comments