python,combinations,permutation,probability

A step by step way to do this would be pairs = {} for first in range(1,7): for second in range(1,7): total = first + second if total in pairs: # If sum exists, add this tuple to the list for this key. pairs[total] += [(first,second)] else: # If sum...

java,algorithm,recursion,permutation,dynamic-programming

I think your mistake is that you pass a single operator to the function permutateSigns instead of giving all operators. Therefore you call the same function twice at the beginning, which results in doubled answers. Here is the corrected code (I think it is what you need) public class ArithmeticGame...

It's called the Cartesian product of two sequences. This is already available in Python as a library function: itertools.product. Example: >>> import itertools >>> a = [1, 2] >>> b = [3, 4, 5] >>> list(itertools.product(a, b)) [(1, 3), (1, 4), (1, 5), (2, 3), (2, 4), (2, 5)] ...

c++,string,permutation,alphabet

Surely the stack would overflow but concentrating on your question even if you write an iterative program it will take a long time ( not an infinite loop just very long ) [26L, 650L, 15600L, 358800L, 7893600L, 165765600L, 3315312000L, 62990928000L, 1133836704000L, 19275223968000L, 308403583488000L, 4626053752320000L, 64764752532480000L, 841941782922240000L, 10103301395066880000L, 111136315345735680000L, 1111363153457356800000L, 10002268381116211200000L,...

python,matrix,random,permutation,shuffle

You need to make a copy of vec before you shuffle it: import random vec=[1,2,3,4,5] for i in range(5): vec.append(10) Matpreferences=[] for i in range(10): v = vec[:] random.shuffle(v) Matpreferences.append(v) Explanation From your code: a=vec Matpreferences.append(a) Here, a points at the same data that vec points at. Consequently, when a...

There's a lot of them. To be clear: Combinations of 123 for 2 digits are 12, 13, 23. Permutations of 123 for 2 digits are 12, 13, 21, 23, 31, 32. Combinations is a smaller number because order doesn't matter. Your code looks like you require at least one number...

c,string,algorithm,math,permutation

As per the comments follow-up, IMO, what you want to understand is swap((a+i), (a+j)); function call. Well, to start with, in void permute() function, you're accepting the first parameter as char *a. So, a is of type char *, and int i, int n are two more integers. Now, while...

haskell,permutation,combinatorics

bhelkir's comment to the question has diagnosed your error correctly, so I'll skip that. The logic of your allCodes function is fundamentally sound (setting aside the permutations vs. combinations issue). One thing that's worth pointing out is that the same effect can be achieved as a one-liner by using two...

algorithm,set,permutation,combinatorics,sequences

What you are looking for is the number of surjective functions whose domain is a set of K elements (the K positions that we are filling out in the output sequence) and the image is a set of S elements (your input set). I think this should work: static int...

python,algorithm,permutation,combinatorics

Doable with a backtracking search. Python 3: import itertools import operator def valid(cols_so_far): for i, col1 in enumerate(cols_so_far): for col2 in cols_so_far[i + 1:]: if any(map(operator.eq, col1, col2)): return False return True def enum(letters, k, cols_so_far=None): if cols_so_far is None: cols_so_far = (tuple(letters),) if not valid(cols_so_far): pass elif len(cols_so_far) ==...

There's nothing wrong with your code (algorithmically), if you intended to implement the Wikipedia pseudocode. You have successfully implemented the algorithm presented. However, the algorithm presented is not Heap's algorithm, and it does not guarantee that successive permutations will be the result of a single interchange. As you can see...

python,algorithm,time-complexity,permutation

I believe there is a proof that the runtime is indeed O(n*n!). (Inspired by an earlier SO question here: complexity of recursive string permutation function) We have the following recursion for the time spent, without printing: T(n) = n*T(n-1) + O(n^2) Now if U(n) = T(n)/n! then we must have...

The following one keep adding changes to the prefix between each iteration in for-loop prefix = prefix + numbers.charAt(i); permutation(prefix,numbers.substring(0, i)+numbers.substring(i+1)); while this one only pass the changes on prefix to the next level of invocation, it match the purpose of this recursive function well permutation(prefix + numbers.charAt(i),numbers.substring(0, i)+numbers.substring(i+1)); To...

matlab,permutation,combinatorics

To assure no indices coincide before and after the shuffle, you can use a rejection method, i.e. keep trying until success: N = 10000; original_indices = 1:N; done = 0; while ~done shuffled_indices = randperm(N); %// this will hold the result when loop is exited done = all(shuffled_indices~=original_indices); end According...

javascript,math,logic,computer-science,permutation

How about: if ((!SL || SM) && (!TL || TM)) ... ie: the source must be empty or take multiple lines and the target must be empty or take multiple lines...

python,sorting,pandas,permutation

Since you're grouping by age, let's do that and return all the permutations for each group and then take the product (using itertools' product and permutation functions): In [11]: age = df.groupby("age") If we look at the permutations of a single group: In [12]: age.get_group(21) Out[12]: age name 2 21...

c++,c,arrays,algorithm,permutation

There is a very simple solution for this: transposition. If two sets are isomorphic, it means a one-to-one mapping exists, where the set of all the numbers at index i in set S1 equals the set of all the numbers at some index k in set S2. My conjecture is...

The permutations of [1, 2, 3] that start with 1 are just the permutations of [2, 3] with 1 added to the front. map (1:) . perm $ [2, 3] ...

Please write a piece of code that takes as an input a list in which each element is another list containing an unknown type and which returns a list of all possible lists that can be obtained by taking one element from each of the input lists. I would...

You can also create a new function getperm to get the permutation index from your generator: def getperm(index,generator): aux=0 for j in generator: if aux == index: return j else: aux = aux +1 In: getperm(15,permute(['A', 'B', 'C', 'D'])) Out: ['C', 'A', 'D', 'B'] ...

sql,sql-server,algorithm,permutation

This is a start. But I don't know if matching only on the count of tag hits is sufficient for your sorting. select p.ProductId, count(*) as Relevance from Product as p inner join ProductTags as pt on pt.ProductId = p.ProductId where pt.TagId in ( select TagId from Tags where TagName...

algorithm,recursion,dynamic,combinations,permutation

EDIT : after seeing the original question, here is the solution which gave correct output for every testcase provided in above question link, if u want give input {60} , u shud give as {60,0,0} . Basic idea is , u need to get all of them less than or...

python,algorithm,iterator,permutation

One possibility is to use an encryption. Since encryption is reversible, i.e. one-to-one, for a given key you will get back the same numbers you encrypt but in a different order. You need a block cypher with a block size large enough to include your maximum N. Use DES in...

I have transliterated your function and I have gotten the following #include <iostream> #include <list> #include <iterator> void arrangements( std::list<char> l, std::list<char> f, size_t k ) { if ( k == 0 ) { for ( char c : l ) std::cout << c << ' '; std::cout << std::endl;...

Since you state Iterating through and removing items is not viable as this needs to scale to very large sizes. The best is to wrap the interator produced by permutations that will generate the tuples you want and skip the tuples you do not want: my_list = [1,2,3,4] def my_perms(my_list,...

Approach I think recursion is the way to go here, where your recursive method looks like this: def recurse(n,t) where n is the number of elements required; and t is the required total. If we let @arr be the array of integers you are given, recurse(n,t) returns an array of...

python,permutation,itertools,dice,cartesian-product

As Calum noted, you should use the built-in itertools for these common loops. In your case, you would want: import itertools results = [sum(x) for x in itertools.product(range(1,5),repeat=9)] range(1,5) represents the 4 sides of the die repeat=9 represents the 9 dice you want to roll See itertools.product for doc...

java,string,recursion,permutation,anagram

Easier example: permutation("", "ABC"), representing empty string as *: * ABC + A BC + AB C - ABC * | | | ` AC B - ACB * | + B AC + BA C - BAC * | | | ` BC A - BCA * | `...

c#,algorithm,random,permutation,shuffle

This works for me: var SourceList = new List<string>() { "Obj_A", "Obj_B", "Obj_C", "Obj_D", "Obj_E", "Obj_F", "Obj_G", }; var rnd = new Random(); var ResultList = Enumerable // create an exceedingly long sequence for retries .Repeat(0, int.MaxValue) // select and randomly order all of the indices of `SourceList` .Select(_ =>...

i got what i want it's from @mudasobwa link. and i edit to what i want. <?php $in = array(1,2,3,4,5,6); $te = power_perms($in); // print_r($te); $thou=0; $hun =0; $pu = 0; for($i=0;$i<count($te);$i++) { $jm = count($te[$i]); for($j=0;$j<$jm;$j++) { $hsl[$i] = $hsl[$i] . $te[$i][$j]; } if($hsl[$i] >=100 && $hsl[$i] < 1000...

IIUC you are trying to find all anagrams of a word in a dictionary. The best way to do this is as follows: 1. Create map from string to list of strings. 2. For each word in dictionary. a. Let sortedWord = sort letters in word lexicographically. b. Add word...

So i think im done N = size(data, 1); r=randperm(N); for ii=1:80 matrix(r(ii),:) =data(ii,:) ; end ...

If you need permutations (your example is not permutations), C++ Standard Library has a perfect function for that - std::next_permutation: string s("ABC"); do { cout << s << endl; } while (next_permutation(s.begin(), s.end())); Note that the range must be sorted coming into the first iteration of this loop in order...

java,arrays,algorithm,permutation,factorial

Creating (or printing) the permutations of an array is much easier done as a combination of recursively and iteratively than purely iteratively. There are surely iterative ways to do it, but it is particularly simple with a combination. Specifically, note that there are by definition N! permutations of a length...

- >> in C#

First, the answer to the question. Please note that after that I will post something that isn't muddled by the data structure that just shows permutation through recursion. private void button1_Click(object sender, EventArgs e) { List<List<KeyValuePair<string, string>>> list = new List<List<KeyValuePair<string, string>>>(); list.Add(new List<KeyValuePair<string, string>>()); list[0].Add(new KeyValuePair<string, string>("Category 1", "Value...

java,algorithm,recursion,graph,permutation

Sure, though this isn't a brilliant algorithm to begin with. If you don't mind, I'll introduce a small change.. First of all a general tip, get rid of that string. Strings are terrible for anything that isn't a string, and you're using it to store an array of integers. Just...

No like Kerrek SB said you can just sort it and take that (ascending by default). std::vector<int> input = { 4, 3, 9, 1 }; std::sort(std::begin(input), std::end(input)); For more info see: std::sort. If you really need all the permutations you could use std::next_permutation on the sorted input and it would...

python,algorithm,list,sorting,permutation

Here's one way to do it. My perms function generates all valid permutations. First I collect the indexes for each element in B, then I recursively build and yield the permutations by always picking one of the still available indexes for each item in A until a permutation is ready...

arrays,variables,random,permutation,probability

You've got an unsorted Array array with n elements. You've got two possible positions for where the local maxima could be. The local maxima could be either on the end or between the first and last element. Case 1: If you're looking at the element in either the first or...

One of the way that i can give the suggestion seeing the code pasted here is that you have some duplicated stuff like this if(list1.Count==0 && list2.Count==0) and then if(list1.Count==0 && list2.Count==0 && list3.Count==0) One of the suggestion will be to per-calculate the condition like this bool onetwo = list1.Count==0...

This will give you one possible instance of the permuted row values: > apply(Data,1,sample) [,1] [,2] [,3] [,4] [,5] [1,] 21 17 8 19 15 [2,] 11 12 18 14 20 [3,] 6 22 23 24 10 [4,] 16 2 3 9 5 [5,] 1 7 13 4 25 Notice...

javascript,permutation,uppercase,lowercase

It's as simple as generating permutations in any language with binary logic. var s = "word"; var sp = s.split(""); for (var i = 0, l = 1 << s.length; i < l; i++) { for (var j = i, k = 0; j; j >>= 1, k++) { sp[k]...

Recording this question and my own finding as I didn't find anything simple enough while searching. Perhaps this may help someone: a = [4, 6, 9] (1..a.length).flat_map { |n| a.permutation(n).to_a } And for every combination, just switch the method, like so: a = [4, 6, 9] (1..a.length).flat_map { |n| a.combination(n).to_a...

sql,arrays,postgresql,combinations,permutation

WITH RECURSIVE A(i) AS (SELECT * FROM unnest(ARRAY['A,B'])), B(j) AS (SELECT * FROM unnest(ARRAY['A','B','C','D'])), cte AS ( SELECT j AS combo, j, 1 AS ct FROM B UNION ALL SELECT cte.combo ||','||B.j, B.j, ct + 1 FROM cte, B WHERE ct <= 4 AND position(B.j in cte.combo) = 0 )...

algorithm,sequence,permutation

The trick here is to index the sequence in binary 1234 ---- 12345 (0000) 12354 (0001) 12453 (0010) 12543 (0011) 13452 (0100) 13542 (0101) 14532 (0110) 15432 (0111) 23451 (1000) 23541 (1001) 24531 (1010) 25431 (1011) 34521 (1100) 35421 (1101) 45321 (1110) 54321 (1111) and then observe that the numbers...

matlab,permutation,combinatorics

The following solution finds all the places in B where zeroes can go (T0), and where ones can go (T1). Then it loops through all those permutations, producing each mapping. A = [0 0 0 1 1 0 1 0]; B = [1 1 0 0 0 0 0 1];...

You can fix your code this way: bitmask |= (1<<i); running_count = running_count + 1; permutations(); running_count = running_count - 1; bitmask &= ~(1<<i); But it would be much better to not rely on global variables. Memory allocation in main is also unnecessary, given the fixed buffer size. Here is...

c,arrays,algorithm,sorting,permutation

In C There's a pretty straightforward description of an algorithm (plus implementation) at geeksforgeeks: Given a string, print all permutations of it in sorted order. For example, if the input string is “ABC”, then output should be “ABC, ACB, BAC, BCA, CAB, CBA”. We have discussed a program to print...

l = [1,'a',12,'b','poppy'] def p(l,t): return [l[i-1] for i in t] print(p(l,(3,4,5,2,1))) [12, 'b', 'poppy', 'a', 1] indexing is 0 based so if you actually wanted to use the indexes for a 5 element list it would be (2,3,4,1,0) and [l[i] for i in t]...

You don't show any code to generate the combinations of numbers that produce a sum. Link to wiki article about partitions . In this case, the goal is to count the number of combinations and/or permutations, which might be possible without actually generating a set of combinations. Not sure if...

What you're talking about are permutations. This can be done in Perl with the Algorithm::Permute module: If you've installed the module, here's a shell one-liner that will do it for you: perl -e' use Algorithm::Permute qw(); my $str = $ARGV[0]; my @arr = split(/\s+/,$str); my $ap = new Algorithm::Permute(\@arr); while...

python,string,recursion,combinations,permutation

Use permutations: from itertools import permutations x = 'god' perms = [] for i in range(1, len(x)+1): for c in permutations(x, i): perms.append("".join(c)) print(perms) # ['g', 'o', 'd', 'go', 'gd', 'og', 'od', 'dg', 'do', 'god', 'gdo', 'ogd', 'odg', 'dgo', 'dog'] ...

python,list,iteration,permutation

You are producing the product of the values, so use itertools.product() with a repeat set: from itertools import product for combo in product(['A', 'B', 'C'], repeat=10): Demo: >>> from itertools import product >>> products = product(['A', 'B', 'C'], repeat=10) >>> next(products) ('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A',...

One way to generate all 'permutations' one at the time in lexicographical order, without having to store them all in memory: function permute_chars(alphabet, nword, nmax) if nargin < 3 % default to displaying all, this can be a huge number! nmax = nchar^nword; end nchar = length(alphabet); ind = zeros(1,...

Initially, I thought I would filter the permutations that have a hamming distance greater than 2. However, if you really only need to generate all the vectors resulting by swapping one pair, it would be more efficient if you do like this: for(int i = 0; i < n; i++)...

The thing is, the list [] in Python is dynamic. So when you add elements to it with array.append(numberList[x]), they stay there forever. Just remove the added element after your recursive call: def permutation(numberList,array,place): if (place==len(numberList)): print(array) else: x=0 while (x < len(numberList)): array.append(numberList[x]) permutation(numberList,array,place+1) array.pop() x+=1 That's actually the...

Using set intersection: import itertools import string numbers = set(range(10)) letters = set(string.ascii_letters) print([x for x in itertools.combinations([0,1,2,3,4,'a','b','c','d'], 4) if set(x) & letters and set(x) & numbers]) ...

# The following will give you a list of fifty data frames, # Each data frame has a 49 row subset of the original listoftables <- apply(combn(1:50, 49), 2, FUN = function(x) df[x,]) ...

sorting,permutation,julia-lang

The following version appears to be relatively space-efficient because it uses only an integer array of the same length as the input array: function selectperm (x,k) z = collect(1:length(x)) return select!(z,1:k,by = (i)->abs(x[i]), rev = true) end x = [-3,-2,4,1,0,-1] k = 3 # num components desired in partial sort...

java,math,combinations,permutation

For R = 1, similar to Fibonacci. F(0) = F(1) = 1 F(N) = F(N-1) + F(N-2) Best solution in Java. static int func(int n) { if (n < 1) return 0; // as you required, F(0) = 0 int n1 = 1, n2 = 1; // however, for F(2..)...

I believe that we've solved our own question. The original problem dealt with origins and destinations not numeric values. So, I've posted that answer - it's an easy switch to numeric. Hope this helps someone in the future. library(dplyr) library(sqldf) x<-data.frame(orig=as.character(sample(LETTERS[1:10], 100, replace=TRUE)), dest=as.character(sample(LETTERS[1:10], 100, replace=TRUE))) x$orig<-as.character(x$orig) x$dest<-as.character(x$dest) x1<-sort(unique(c(x[,1], x[,2])))...

matrix,permutation,eigen,sparse

If you want to apply a symmetric permutation P * Y * P^-1, then the best is to use the twistedBy method: SpMat z = y.twistedBy(perm); otherwise you have to apply one and then the other: SpMAt z = (perm * y).eval() * perm; ...

python,recursion,permutation,nested-lists

from itertools import * combo_list = [] for i in your_list: for j in permutations(i, len(i)): combo_list.append(j) ...

excel,combinations,permutation

Place the items to your worksheet in the first three columns like this A B C pizza wine ice pasta beer fruits lasagne water Then, you can get the combinations in F, G, H using the following formulae. F1: =IF(ROW()-ROW($F$1)+1<=COUNTA(A:A)*COUNTA(B:B)*COUNTA(C:C), INDEX(A:A,INT((ROW()-ROW($F$1))/(COUNTA(B:B)*COUNTA(C:C))+1)), "") G1: =IF(ROW()-ROW($F$1)+1<=COUNTA(A:A)*COUNTA(B:B)*COUNTA(C:C), INDEX(B:B,MOD(ROW()-ROW($F$1),COUNTA(B:B))+1), "") H1: =IF(ROW()-ROW($F$1)+1<=COUNTA(A:A)*COUNTA(B:B)*COUNTA(C:C),...

python,algorithm,permutation,probability

import itertools mystring = 'abcde' for i in range(1,len(mystring)+1): for combo in itertools.combinations(mystring, i): print(''.join(combo)) Output: a b c d e ab ac ad ae bc bd be cd ce de abc abd abe acd ace ade bcd bce bde cde abcd abce abde acde bcde abcde ...

The number of compositions of n into k nonnegative summands is (n+k-1) choose n by the stars-and-bars method. You have k=n, so the count is 2n-1 choose n. Your examples were 3C2=3 and 5C3=10.

python,algorithm,list,unique,permutation

Use itertools.product to generate all possible combinations from the lists. Then, using itertools.ifilter, filter out all combinations that contain a repeated character. One simple way to do this is to check if the length of the list stays the same if you remove all duplicates (i.e. if you create a...

r,time-series,permutation,quantmod

If you wanted to get a list of data frames, one for each pair, you could try: dfs <- lapply(seq_len(ncol(perm)), function(x) close[,paste0(perm[,x], ".Close")]) Now you can get the 2-column data frames for each pair with dfs[[1]], dfs[[2]], etc. You can perform statistical analyses on each pair using the lapply function....

r,algorithm,function,permutation,combinatorics

Lets first choose a representative for each equivalence class. Lets say that vector p = {x_1 ... x_k} is a representative if it is lexicographical minimum from all p_i such that p_i ~ p. Notice that x_i is in range (1..x_j + 1) forall j < i. If that doesn't...

I think that select/3 should do (at least this seems to match the required outcome) special_permutation(L, [H|R]) :- select(H, L, R). ...

python,list,dictionary,permutation,itertools

You can use dictionary expression data = [['cups', 'cusp', 'cpus', 'cpsu', 'csup', 'cspu',], ['pups', 'pusp','upsp', 'upps', 'upsp', 'uspp']] result = {each[0]:each[1:] for each in data} print result Yields: {'pups': ['pusp', 'upsp', 'upps', 'upsp', 'uspp'], 'cups': ['cusp', 'cpus', 'cpsu', 'csup', 'cspu']} ...

algorithm,permutation,discrete-mathematics,lexicographic

You can do it this way: // n is the number of elements in the given sequence p = all permutations of [0, 1, ..., n - 1] in lexicographical order for permutation in p: for i = 0 ... n - 1 print(s[permutation[i]]) // s is the given sequence...

You have declared your function inside the main block, which is causing the compilation error. Declare it outside as- #include <cctype> #include <iostream> #include <string> using namespace std; void permutation(string s, int i, int n) { int j; if (i == n) cout << s << "\t"; else { for...

The Wiki page shows an if-else that's missing from your code. The one if that you have does something completely different. Also, I'd add a std::endl after the cout, and try with the input 1 2 3 4. The linked article has a line-by-line example of the algorithm running for...

you can use recursion or backtracking, it saves you all the pain of nested loops(yes, this function takes time to run!) This article explains this well. good luck!

python,string,algorithm,permutation

We can count the zeroes. Then we remove the zeroes from the number, we sort it and reassemble it. To reassemble we use the first digit, then we add back our zeroes and then the rest of our sorted number. num = '56340902138765401345' nzeros = num.count('0') num = ''.join(sorted(num.replace('0', '')))...

algorithm,recursion,permutation

A common approach is as follows. If you have, say, K bins, then add K-1 special values to your initial array. I will use the -1 value assuming that it never occurs in the initial array; you can choose a different value. So for your example the initial array becomes...

php,multidimensional-array,permutation

This is you are trying to do , use Permutation of array in php i. e Cartesian product of array. function cartesian($input) { $result = array(); while (list($key, $values) = each($input)) { if (empty($values)) { continue; } if (empty($result)) { foreach($values as $value) { $result[] = array($key => $value); }...

javascript,arrays,algorithm,recursion,permutation

I'm assuming that you're not looking for a complete working implementation but rather the errors in your code. Here are some I found: You are not keeping variable names consistent: holdingArray vs holdingArr. You never actually push anything into singleSolution. Edit: Here's a working implementation, based on your original code....

One simple solution is to use a set to know which numbers you already used and which ones you didn't: def permutation(numberList,array,visited,place): if (place==len(numberList)): print array else: i=0 while (i < len(numberList)): if i not in visited: visited.add(i) array.append(numberList[i]) permutation(numberList,array,visited,place+1) array.pop() visited.remove(i) i+=1 def scanList(): numberList=[]; number=input() #keep scanning for...

Have a look at the itertools.permutations function. Then it's simply merging the strings, parsing as int and multiplying them until you find the right one. Alternatively you can factorize N and then test if the pair of factors contains all the digits in S from itertools import permutations from numpy...

With STL, the code may be: std::vector<std::vector<int> > permuteUnique(std::vector<int> num) { std::sort(num.begin(), num.end()); std::vector<std::vector<int> > res; if(num.empty()) { return res; } do { res.push_back(num); } while (std::next_permutation(num.begin(), num.end())); return res; } Live demo Your test is not sufficient to skip duplicates. For entry {2, 1, 1}, you got: {2, 1,...

It is an array of booleans. Once you find an unused character (used[i] is false), append it to out, flag it as used (used[i]=true) & permute() what is left. Once that is done, mark it as unused (used[i]=false) & remove the character you appended to out (out.setLength(out.length()-1)), so your...

Something like this? import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MatrixCross { public static void cross(String[]... matrix){ cross(0,matrix, Collections.EMPTY_LIST); } private static void cross(int index,String[][] matrix, List<String> result){ if (index >= matrix.length){ System.out.println("<test>"); int i = 1; for (String str : result) { System.out.println(" <test_"+i+">"+str+"</test_"+i+">"); i++; } System.out.println("</test>"); }...

php,arrays,combinations,permutation

Alright - all possible subsets without duplicates and assuming that the order does not matter, i.e. [1, 2, 3, 4, 5] is the same as [5, 4, 3, 2, 1]. Minimalistic example: <?php $arr = array(1, 2, 3, 4, 5, 6, 7); function getSubsets($set, $items) { $result = array(); getSubsets2($set,...

Is this what you're looking for? function permute($str,$i,$n) { if ($i == $n && strpos($str, 'yy') === false) // note the extra condition { print "$str\n"; } else { for ($j = $i; $j < $n; $j++) { swap($str,$i,$j); permute($str, $i+1, $n); swap($str,$i,$j); // backtrack. } } } If this...

algorithm,permutation,powerset

Algorithm to generate all possible permutations of a list? It's a complicated algorithm any way you want to do it, I think recursively is the fun way. The recursive way basically removes one element, calls the recursion on the shortened list, then returns the recursive result with the removed element...

c,string,recursion,permutation

This is a classic interview question, the solution goes something like that: int permu(char* str, size_t len ,size_t index ) { size_t i = index - 1; if(index == len) { printf ("%s\n",str); } while (++i < len) { swap (str,index,i); /* swap between index and i */ permu(str, len...

r,algorithm,matrix,permutation

Basically what you want is permutation of multiset. The package iterpc will do the job. > library(iterpc) > I <- iterpc(c(3,7), ordered=TRUE) > getlength(I) [1] 120 > getall(I) [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [1,] 1 1 1 2 2 2 2 2 2 2 [2,]...

python,performance,algorithm,permutation

def cycling(p, start, done): while not done[e]: done[e] = True e = p[e] yield e def toCycle(p): done = [False]*len(p) cycles = [tuple(cycling(p, 0, done))] while not all(done): start = done.index(False) cycles.append(tuple(cycling(p, start, done))) return cycles With your example my code runs about 30% faster than yours....