Generate all permutations of a list without adjacent equal elements

This is along the lines of Thijser’s currently incomplete pseudocode. The idea is to take the most frequent of the remaining item types unless it was just taken. (See also Coady’s implementation of this algorithm.) import collections import heapq class Sentinel: pass def david_eisenstat(lst): counts = collections.Counter(lst) heap = [(-count, key) for key, count in … Read more

Get all permutations of a PHP array?

function pc_permute($items, $perms = array()) { if (empty($items)) { echo join(‘ ‘, $perms) . “<br />”; } else { for ($i = count($items) – 1; $i >= 0; –$i) { $newitems = $items; $newperms = $perms; list($foo) = array_splice($newitems, $i, 1); array_unshift($newperms, $foo); pc_permute($newitems, $newperms); } } } $arr = array(‘peter’, ‘paul’, ‘mary’); pc_permute($arr); or … Read more

Set partitions in Python

Since this nice question has been brought back to life, here’s a fresh answer. The problem is solved recursively: If you already have a partition of n-1 elements, how do you use it to partition n elements? Either place the n‘th element in one of the existing subsets, or add it as a new, singleton … Read more