POV-Ray : Newsgroups : povray.off-topic : Understanding std::next_permutation Server Time
5 Sep 2024 21:25:57 EDT (-0400)
  Understanding std::next_permutation (Message 1 to 1 of 1)  
From: Darren New
Subject: Understanding std::next_permutation
Date: 1 Apr 2009 18:16:55
Message: <49d3e7d7$1@news.povray.org>
I wrote a Python version of std::next_permutation with bunches of output, 
and I see what it's doing now. It's really rather clever.

C++, Python, and sample output:
http://darren.s3.amazonaws.com/permutations.zip

There's a loop that finds the first in-order pair of numbers, working from 
back to front. That's the
   while (true) { ii = i; i--; ... }
part, which doesn't stop until *i<*ii or you run off the front of the sequence.

If you run off the front, then every pair of numbers is out of order, so you 
have the lexically highest permutation, so you say "all done".

Otherwise, having found the pair of numbers out of order, you then find a 
'j' bigger than 'i'. Swap those two, then reverse the list to the right of 'i'.

It's sort of like doing a bubble sort, except you only sort things to the 
right of the first out of order element, and then you reverse the right half 
again, just to keep it maximally unsorted at each step.

-- 
   Darren New, San Diego CA, USA (PST)
   There's no CD like OCD, there's no CD I knoooow!


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.