81 lines
2.4 KiB
Python
81 lines
2.4 KiB
Python
import time
|
||
from itertools import permutations
|
||
from typing import Tuple
|
||
|
||
import numpy as np
|
||
import numpy.typing as npt
|
||
|
||
from common import plot_plan, read_data
|
||
|
||
|
||
def exhaustive_search(distances: npt.NDArray) -> Tuple[float, npt.NDArray]:
|
||
"""An implementation of exhaustive search.
|
||
|
||
This implementation takes a permutation iterator, then maps each
|
||
element to a tuple containing the travel distance of that permutation
|
||
and the permutation tuple itself. Finally the function returns the
|
||
tuple that contains the smallest travel distance.
|
||
|
||
Args:
|
||
distances (npt.NDArray): An array containing distances to travel.
|
||
|
||
Returns:
|
||
Tuple[float, npt.NDArray] A tuple containing the shortest travel
|
||
distance and its corresponding permutation.
|
||
"""
|
||
|
||
size = len(distances)
|
||
|
||
return min( # Find the smallest travel distance from the array
|
||
map( # Map the permutation array to contain tuples (distance, permutation)
|
||
lambda perm: (
|
||
sum([distances[perm[i - 1], perm[i]] for i in range(size)]),
|
||
np.array(perm),
|
||
),
|
||
permutations(range(size)),
|
||
),
|
||
)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
cities, data = read_data("./european_cities.csv")
|
||
|
||
# A loop timing finding the optimal solution for different n
|
||
for n in range(6, 11):
|
||
# Time exhaustive search
|
||
t0 = time.time_ns()
|
||
distance, perm = exhaustive_search(data[:n, :n])
|
||
t1 = time.time_ns()
|
||
|
||
time_elapsed_ms = (t1 - t0) / 1_000_000.0
|
||
|
||
print(f"Exhaustive search for the {n} first cities:")
|
||
print(f"distance : {distance:>12.6f}km")
|
||
print(f"time to find solution: {time_elapsed_ms:>12.6f}ms\n")
|
||
|
||
|
||
"""Running example
|
||
|
||
oblig1 on main [?] via 🐍 v3.12.6 took 7s
|
||
❯ python exhaustive_search.py
|
||
Exhaustive search for the 6 first cities:
|
||
distance : 5018.810000km
|
||
time to find solution: 1.105330ms
|
||
|
||
Exhaustive search for the 7 first cities:
|
||
distance : 5487.890000km
|
||
time to find solution: 10.089604ms
|
||
|
||
Exhaustive search for the 8 first cities:
|
||
distance : 6667.490000km
|
||
time to find solution: 78.810508ms
|
||
|
||
Exhaustive search for the 9 first cities:
|
||
distance : 6678.550000km
|
||
time to find solution: 765.676230ms
|
||
|
||
Exhaustive search for the 10 first cities:
|
||
distance : 7486.310000km
|
||
time to find solution: 8281.795515ms
|
||
"""
|