summaryrefslogtreecommitdiffstats
path: root/tour_improvements/random_swapping.py
blob: 3fc88bcbf5adc156182345dd72dfa5dab739aedc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from graph import calculate_route
from random import sample

# For swapping once
def random_swap(route: list) -> list:
    r = route[:]

    a, b = sample(range(0, len(r) - 1), 2)

    temp = r[b]
    r[b] = r[a]
    r[a] = temp

    return r

# check and swap if better n times
def random_swapping(route: list, n: int) -> list:
    d = calculate_route(route)
    r = route[:]

    for _ in range(n):

        random_swap_route = random_swap(r)

        if calculate_route(random_swap_route) < d:
            r = random_swap_route

    return r