From eec6c225100fd785f41da23cd87098a8c6ddd863 Mon Sep 17 00:00:00 2001 From: dclavijo Date: Thu, 8 Feb 2024 12:52:51 -0300 Subject: [PATCH] add Heap's algorithm --- heaps.py | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 heaps.py diff --git a/heaps.py b/heaps.py new file mode 100644 index 0000000..038b1db --- /dev/null +++ b/heaps.py @@ -0,0 +1,35 @@ +# implementation based on https://en.wikipedia.org/wiki/Heap%27s_algorithm +# Copyright DarĂ­o Clavijo 2024 + +from sympy import factorial +from sympy.combinatorics import Permutation + +def heaps(k, A): + if k == 1: + yield A + else: + for i in range(0, k): + yield from heap(k-1, A) + if k & 1 == 0: + A[i],A[k-1] = A[k-1],A[i] + else: + A[0],A[k-1] = A[k-1],A[0] + + +def heaps_count_swaps(k, A): + c = 0 + if k == 1: + return 0 + else: + for i in range(0, k): + c += heaps_count_swaps(k-1, A) + if k & 1 == 0: + A[i],A[k-1] = A[k-1],A[i] + else: + A[0],A[k-1] = A[k-1],A[0] + c += 1 + return c + + +A038156 = lambda n: heaps_count_swaps(n, list(range(0,n))) +