diagonal distance heuristic in python

Here's an implementation of diagonal distance heuristic in Python:

main.py
import math

def diagonal_distance(current, goal):
    dx = abs(current[0] - goal[0])
    dy = abs(current[1] - goal[1])
    return max(dx, dy) + (math.sqrt(2) - 1) * min(dx, dy)
179 chars
7 lines

This diagonal_distance function takes two tuples representing the current position and the goal position in a 2-dimensional grid. It calculates the horizontal and vertical distances between them and takes the max of those distances. It also calculates the diagonal distance using the Pythagorean theorem (i.e., math.sqrt(dx**2 + dy**2)) and subtracts the max distance from it multiplied by math.sqrt(2) - 1. The resulting value is the diagonal distance heuristic, which is an approximation of the actual distance between the two positions and is commonly used in pathfinding algorithms such as A*.

gistlibby LogSnag