r/badcode • • May 11 '22

python It works but.... NSFW

Post image
475 Upvotes

57 comments sorted by

View all comments

18

u/randomsmiteplayer May 11 '22

I’m looking at it and there’s an ID statement for player == 1. Then immediately afterwards, assign 1 to player. Redundant isn’t it? Am I missing something?

28

u/jomanning May 11 '22

Yes you’re missing something. it’s toggling between player 1 and 2.

If player 1 -> become player 2 Else -> become player 1

7

u/randomsmiteplayer May 12 '22

Yup I see it now. I'm the badcode now!

3

u/EvilStevilTheKenevil May 12 '22

A neat way of avoiding this if statement would be to have player_1 == 1 and player_2 == -1. At the end of each turn, multiply the number by -1.

I'd imagine it doesn't make much of a difference here (I mean if you really cared about performance you wouldn't be using Python), but "if" statements can screw up pipelining, which, for not-so-trivial programs, can dramatically slow down execution.

2

u/MrJankles May 30 '22

Easier than the solution I was thinking of

player = (player+1) % 2

1

u/EvilStevilTheKenevil May 30 '22

This also works, but the modulus operator involves division. If the compiler doesn't recognize %2 as logically equivalent to a bitwise operation on the least significant bit then this might slow things down.

 

Multiplication is as simple as several adders chained together with some bit-shifting for their inputs, and you could somewhat easily implement this algorithm entirely in hardware such that any two 64 bit ints could be multiplied together in a single cycle (floats would be slightly more complicated, but more or less the same).

Meanwhile, division is very complicated (relative to the other 3 fundamental arithmetic operations you learn in grade school, anyway), and there are many different algorithms out there which can get the job done. The naive approaches converge linearly, and some of the more interesting ones do it quadratically, but in any case division is likely to be a multi-cycle operation. In other words, slow.

1

u/LuckyNumber-Bot May 30 '22

All the numbers in your comment added up to 69. Congrats!

  2
+ 64
+ 3
= 69

Click here to have me scan all your future comments.
Summon me on specific comments with u/LuckyNumber-Bot.