Skip to content

Instantly share code, notes, and snippets.

@walac
Created August 22, 2012 00:07
Show Gist options
  • Save walac/3420676 to your computer and use it in GitHub Desktop.
Save walac/3420676 to your computer and use it in GitHub Desktop.
An ugly "hurry up" implementation of NextPermutation algorithm in Mathematica
Vk[p_List] :=
Module[{r =
DeleteCases[
MapIndexed[If[#1[[1]] < #1[[2]], Length[p] - First[#2]] &,
Reverse@Partition[p, 2, 1]], Null]},
If[Length[r] > 0, First[r], Null]]
Vl[p_List, k_Integer] :=
Module[{r =
DeleteCases[
MapIndexed[If[p[[k]] < #1, Length[p] - First[#2] + 1, Null] &,
Reverse[p]], Null]}, If[Length[r] > 0, First[r], Null]]
NextPermutation[p_List] :=
Module[{k = Vk[p], l, vk, vl, t},
If[k === Null, Null, l = Vl[p, k];
If[l === Null, Null, vk = p[[k]]; vl = p[[l]];
t = ReplaceAll[p, {vk -> vl, vl -> vk}];
Join[t[[1 ;; k]], Reverse[t[[k + 1 ;; All]]]]]]]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment