elikaski / BF-it

A C-like language to Brainfuck compiler, written in Python
MIT License
121 stars 11 forks source link

Improve get_set_cell_value_code #40

Closed NeeEoo closed 3 years ago

NeeEoo commented 3 years ago

Here is my test code plus the result of it. https://gist.github.com/NeeEoo/1057b888f74f85fe22cfb36de89ffd73

NeeEoo commented 3 years ago

The algorithm starts at 2(offset // 2) and narrows it down until left and right results in a product that is closest to the wanted value. This is basically a factor algorithm but it gets the smallest difference between leftright and offset.

Edit: meant 2(offset // 2) not 1(offset // 2 - 1)

NeeEoo commented 3 years ago

Which would you prefer, or do you have a better way to do this

looped += get_char(-c if is_negative else c) * abs(c)  # c more actions
looped += get_char(c * (int(is_negative) * -2 + 1)) * abs(c)  # c more actions

(int(is_negative) * -2 + 1) returns -1 if is_negative is true otherwise return 1

I have fixed the issue where the loop wont run if offset == 0/1/2/3. But i haven't pushed it yet.

elikaski commented 3 years ago

OK, following your link to your getset.py, I'm convinced your code is better than mine 😄 I reviewed it again and now I understand it It looks OK to me, I'm ready to merge

Regarding your question,

looped += get_char(-c if is_negative else c) * abs(c)  # c more actions

I think this one is more readable, but choose whatever you prefer

Please let me know when you're ready for me to merge Thank you :)

elikaski commented 3 years ago

Thanks! Your change increases performance and makes the generated code shorter :)