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

How to generate permutations or combinations of object in R?

A Walk Through a Slice of Combinatorics in R* Below, we examine packages equipped with the capabilities of generating combinations & permutations. If I have left out any package, please forgive me and please leave a comment or better yet, edit this post. Outline of analysis: Introduction Combinations Permutations Multisets Summary Memory Before we begin, … Read more

Generating all distinct permutations of a list in R

A while back I had to do this in base R without loading any packages. permutations <- function(n){ if(n==1){ return(matrix(1)) } else { sp <- permutations(n-1) p <- nrow(sp) A <- matrix(nrow=n*p,ncol=n) for(i in 1:n){ A[(i-1)*p+1:p,] <- cbind(i,sp+(sp>=i)) } return(A) } } Usage: > matrix(letters[permutations(3)],ncol=3) [,1] [,2] [,3] [1,] “a” “b” “c” [2,] “a” “c” … Read more

JavaScript – Generating combinations from n arrays with m elements [duplicate]

Here is a quite simple and short one using a recursive helper function: function cartesian(…args) { var r = [], max = args.length-1; function helper(arr, i) { for (var j=0, l=args[i].length; j<l; j++) { var a = arr.slice(0); // clone arr a.push(args[i][j]); if (i==max) r.push(a); else helper(a, i+1); } } helper([], 0); return r; } … Read more

permutations with unique values

class unique_element: def __init__(self,value,occurrences): self.value = value self.occurrences = occurrences def perm_unique(elements): eset=set(elements) listunique = [unique_element(i,elements.count(i)) for i in eset] u=len(elements) return perm_unique_helper(listunique,[0]*u,u-1) def perm_unique_helper(listunique,result_list,d): if d < 0: yield tuple(result_list) else: for i in listunique: if i.occurrences > 0: result_list[d]=i.value i.occurrences-=1 for g in perm_unique_helper(listunique,result_list,d-1): yield g i.occurrences+=1 a = list(perm_unique([1,1,2])) print(a) result: [(2, … Read more