3

I am writing a function to scan a specific map (2D array). In order to avoid scanning spots outside of the array, I wrote a few if statements, but it feels like the wrong, long, inefficient way of doing it.

H is the map's height value, int W is for width, int c is the current spot, a tuple containing x and y values.

 floorH = c[0]-D
 floorW = c[1]-D
 ceilingH = c[0]+D+1
 ceilingW = c[1]+D+1
 if floorH < 0:
 floorH = 0
 if floorW < 0:
 floorW = 0
 if ceilingH > H:
 ceilingH = H
 if ceilingW > W:
 ceilingW = W

How can I write this better?

Thanks in advance :)

asked Feb 12, 2019 at 17:06

2 Answers 2

8

Instead of using conditionals you could just use the max and min functions.

floorH = c[0]-D
floorW = c[1]-D
ceilingH = c[0]+D+1
ceilingW = c[1]+D+1
floorH = max(floorH, 0)
floorW = max(floorW, 0)
ceilingH = min(ceilingH , H)
ceilingW = min(ceilingW , W)

Actually you can make it even shorter:

floorH = max(c[0]-D, 0)
floorW = max(c[1]-D, 0)
ceilingH = min(c[0]+D+1, H)
ceilingW = min(c[1]+D+1, W)
answered Feb 12, 2019 at 17:11
2
  • 1
    This is the one I use. My teammates and I find it easier to read and less prone to boundary errors. Commented Feb 12, 2019 at 17:22
  • 1
    This is exactly what I was looking for. Thank you! Commented Feb 12, 2019 at 20:43
1

You can format your if like this to save space:

floorH = c[0]-D if c[0]-D > 0 else 0
floorW = c[1]-D if c[1]-D > 0 else 0
ceilingH = c[0]+D+1 if c[0]+D+1 < H else H
ceilingW = c[1]+D+1 if c[1]+D+1 < W else W
answered Feb 12, 2019 at 17:14

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.