Skip to content Skip to sidebar Skip to footer

Python: How To Compute The Distance Between Cells?

Let's suppose I want to compute the distance between cells in a square grid 5x5. The distance between two cells is 100m. Each cell of the grid is number between 0 and 24 0 1 2

Solution 1:

# n1, n2 = cell numbers
cellsize = 100.0
x1,x2 = n1%gs, n2%gs
y1,y2 = n1//gs, n2//gs
dist = sqrt( float(x1-x2)**2 + float(y1-y2)**2)  # pythagoras theorem
dist *= cellsize

Solution 2:

you should consider co-ordinate and not the cell number

gs = 5## Cells per side
S = gs*gs ## Grid Size
r0 = 100## distance between two cellsfor i inrange(0, S):
    for j inrange(0, S):
        if i == j: continue
           xi = int(i/gs)
           yi = i % gs
           xj = int(j/gs)
           yj = j % gs
           dist = r0 * (abs(xi-xj) + abs(yi-yj))

Solution 3:

this is a way to do that:

r = 100

grid = ((0,   1,  2,  3,  4),
        (5,   6,  7,  8,  9),
        (10, 11, 12, 13, 14),
        (15, 16, 17, 18, 19),
        (20, 21, 22, 23, 24))

defcoord(n):
    for x, line inenumerate(grid):
        if n notin line:
            continue
        y = line.index(n)
        return x, y

defdist(n, m):
        xn, yn = coord(n)
        xm, ym = coord(m)
        return r * (abs(xn - xm) + abs(yn - ym))

print(dist(0, 3))  # 300print(dist(2, 7))  # 100print(dist(11, 19)) # 400

the idea is to get the coordinates of your numbers first and then calculating the 'distance'.

Solution 4:

This should work for you

n = 5# row length in arraydefdistance(a, b):
    distance = (abs(a // n - b // n) + abs(a % n - b % n)) * 100return"distance between cell %s and %s is %s" % (a, b, distance)

print(distance(0, 3))
print(distance(2, 7))
print(distance(11, 19))

Output:

distance between cell 0 and 3 is 300
distance between cell 2 and 7 is 100
distance between cell 11 and 19 is 400

Where a and b are your cells, and n is a length of the row in array, in your example is 5.

Solution 5:

We just need to get the row and column number of every number. Then a difference b/w the two and multiplied by 100 will give you answer

defget_row_col(num):
    for i,g inenumerate(grid):
        if num in g:
            col = g.index(num)
            row = i
    return row, col

num1 = get_row_col(11)
num2 = get_row_col(19)
print (abs(num1[0] - num2[0])*100) + (abs(num1[1]-num2[1])*100)

One can enhance this code to check if number is present or not.

Post a Comment for "Python: How To Compute The Distance Between Cells?"