开发者

How can this very long if-statement be simplified?

开发者 https://www.devze.com 2023-01-23 13:00 出处:网络
How ca开发者_Go百科n this if-statement be simplified? It makes a plus sign: http://i.stack.imgur.com/PtHO1.png

How ca开发者_Go百科n this if-statement be simplified? It makes a plus sign: http://i.stack.imgur.com/PtHO1.png

If the statement is completed, then a block is set at the x and y coordinates.

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        if (x%5 == 2 or x%5 == 3 or x%5 == 4) and \
            (y%5 == 2 or y%5 == 3 or y%5 == 4) and \
            not(x%5 == 2 and y%5 == 2) and \
            not(x%5 == 4 and y%5 == 2) and \
            not(x%5 == 2 and y%5 == 4) and \
            not(x%5 == 4 and y%5 == 4):
            ...


This is the same:

if (x % 5 == 3 and y % 5 > 1) or (y % 5 == 3 and x % 5 > 1): 


Basically you're tiling a 5x5 binary pattern. Here's a clear expression of that:

pattern = [[0, 0, 0, 0, 0],
           [0, 0, 0, 0, 0],
           [0, 0, 0, 1, 0],
           [0, 0, 1, 1, 1],
           [0, 0, 0, 1, 0]]

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        if pattern[x%5][y%5]:
           ...

This is a very simple and general approach which would allow the pattern to be easily modified.


There are two trivial fixes:

  • Cache the result of x % 5 and y % 5
  • Use in or chained < to test the values:

Additionally, the test for <= 4 (or < 5) is actually redundant because every value of lx and ly will be < 5.

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        lx = x % 5 # for local-x
        ly = y % 5 # for local-y
        if lx > 1 and y > 1 and \
           not (lx == 2 and ly == 2) and \
           not (lx == 4 and ly == 2) and \
           not (lx == 2 and ly == 4) and \
           not (lx == 4 and ly == 4):

Or you may just keep a list of the actually allowed tuples:

cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        if (x % 5, y % 5) in cross_fields:


Building on Konrad's answer, you can simplify it further:

for y in range(MAP_HEIGHT):
    for x in range(MAP_WIDTH):
        lx = x % 5 # for local-x
        ly = y % 5 # for local-y
        if (1 < lx < 5 and 1 < y < 5 and 
           (lx, ly) not in ((2, 2), (4, 2), (2, 4), (4, 2))):


Konrad's second answer:-

cross_fields = [(2, 3), (3, 2), (3, 3), (3, 4), (4, 3)]

for y in range(MAP_HEIGHT):
  for x in range(MAP_WIDTH):
    if (x % 5, y % 5) in cross_fields:

is probably the best one.

However, I'll contribute:-

for y in range(MAP_HEIGHT):
  for x in range(MAP_WIDTH):
    lx = x % 5
    ly = y % 5
    if (lx > 1 and ly == 3) or (ly > 1 and lx == 3):


The general solution to optimizing a logic function like this is a Karnaugh map. Your truth table would be the literal plus shape you want with rows and columns being your modular tests.

0

精彩评论

暂无评论...
验证码 换一张
取 消