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 :)

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)
Sign up to request clarification or add additional context in comments.

2 Comments

This is the one I use. My teammates and I find it easier to read and less prone to boundary errors.
This is exactly what I was looking for. Thank you!
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

Comments

Your Answer

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.