algorithm,sorting,combinations,combinatorics,gray-code

While I really appreciate the efforts from @tucuxi and @David Eisenstadt, I found some issues with the Hamiltonian approach, namely that it didn't solve for certain values of n and k and certain elements were also unnecessarily discriminated. I decided to give the ideas listed in my question a go...

You could use do.call and expand.grid: do.call(expand.grid, lapply(x, function(y) c(y, -y))) # Var1 Var2 Var3 Var4 # 1 1 2 3 4 # 2 -1 2 3 4 # 3 1 -2 3 4 # 4 -1 -2 3 4 # 5 1 2 -3 4 # 6 -1 2...

c++,string,combinations,powerset,lexicographic

This is a simple recursive approach: #include <string> #include <iostream> using namespace std; void get( string str, string res ) { cout << res << endl; for( int i = 0; i < str.length(); i++ ) get( string(str).erase(i,1), res + str[i] ); } int main( int argc, char **argv) {...

php,arrays,matrix,combinations

This should work for you: So what does this code do? 1. How many combinations are there? So first the question how many combinations are there? And the answer is you have to multiply the amount of every array with each other. So (c = amount1): carray 1 * carray...

haskell,functional-programming,tuples,combinations,idiomatic

What about: [ (x,y) | (x:rest) <- tails xs , y <- rest ] ...

java,arrays,random,combinations

Here is some code which creates 10 random pairs from your input a[] and b[] arrays, and stores them into an HashSet which you can use later as you see fit. The HashSet will automatically remove duplicate pairs. public class Pair { int x; int y; public Pair(int x, int...

You''ll probably have to sort by row first and then simply aggregate, here's a possible solution u[1:2] <- t(apply(u, 1, function(x) sort(x[1:2]))) aggregate(cnt ~., u, sum) # str_statn end_statn cnt # 1 42 106 30 # 2 3 6 202 # 3 4 14 1 ...

php,arrays,function,combinations

This will do it and it's flexible. <?php $length = 7; $totalCombos = pow(2, $length); for($x = 0; $x < $totalCombos; $x++) { echo str_pad(decbin($x), $length, 0, STR_PAD_LEFT) . PHP_EOL; } ...

c++,string,character,combinations

As Bathsheba said, we need to substitute characters with bits. And then iterate on all possible values that bits could make. My example works only on short strings with legth less than 31. If you need more, use std::bitset container. #include <iostream> #include <string> #include <vector> std::vector<std::string> f(const std::string &...

perl,passwords,combinations,system-calls,brute-force

Brute force password cracking is very inefficient, so not really useful except as proof of concept. You've a 4 character alphabetical password, which is a fairly trivial case. First off - you can write: my @alpha =( "a".."z" ); generating the words as you're doing will work, but you'll be...

Actually I think using next_permutation is much better, as you said : void Part::select_assignement(std::vector<MyObject> & vector1, std::vector<MyObject> & vector2 ){ std::map<MyObject,MyObject> assignement; do { j++; assignement.clear(); for (size_t i = 0; i < vector1.size(); ++i) assignement[vector1[i]] = vector2[i]; treat_this_case(assignement); }while(std::next_permutation(vector2.begin(), vector2.end())); } It seems to me that it does exactly...

python,list,combinations,itertools

Using zip, itertools.product and list comprehension: >>> import itertools >>> a = ['A','B','C','D'] >>> b = ['a','b','c','d'] # [x.lower() for x in a] >>> [list(x) for x in itertools.product(*zip(a, b))] [['A', 'B', 'C', 'D'], ['A', 'B', 'C', 'd'], ['A', 'B', 'c', 'D'], ['A', 'B', 'c', 'd'], ['A', 'b', 'C', 'D'],...

php,arrays,string,function,combinations

This should work for you and even without evil(). So what does this code do? 1. How many combinations are there? Pretty simple: nl = amount of combinations Where n is the amount of words and l the length of each combination. So for this specific example there are 3...

javascript,jquery,events,javascript-events,combinations

Just use on instead? You can register as many listeners as you like w/o worry about overwrite. $('#bind-example').on('click', function(){alert('First click!'); }); $('#bind-example').on('click', function(){alert('Second click!'); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="bind-example" href="#">Click Me!</a> If I've misunderstood your question please let me know....

You caught me on a day where I don't want to do what I'm supposed to be doing1. The code below only generates token output; it doesn't attempt to store tokens anywhere. You can redirect the output to a file, but as others have pointed out, you're going to need...

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 )...

This should work for you, easy and simple: What does this code do? 1. Data part In the data part I just define the string and the replacement's for the single character with a associative array (search character as key, replacement as value). 2. getReplacements() function This function get's all...

java,methods,arraylist,integer,combinations

Try using: values.add(array.clone()); Every add of the same array just points to that array object. As you keep changing the same object, the final state is what is being shown for all stored elements. The print works as it just dumps the state of the array at that particular instant....

matlab,matrix,combinations,combinatorics,cartesian-product

You were on the right track with allcomb. You are in fact looking for the cartesian product: [e0, e1, e2] x [e0, e1, e2] x [e0, e1, e2] == [e0, e1, e2]^3. You don't need allcomb though, as ndgrid can already do this. Let's start with your code. It has...

javascript,php,algorithm,numbers,combinations

I feel like the most elegant way to handle this challenge is via recursion. function getCombos(target, min, max, n) { var arrs = []; if (n === 1 && target <= max) { arrs.push([target]); } else { for (var i = min; i < target / n && i <=...

One option, using dplyr's count function: library(dplyr) count(df, Auto, MtgHe, Personal, Other, None) %>% ungroup() #Source: local data frame [4 x 6] # # Auto MtgHe Personal Other None n #1 0 0 0 0 1 3 #2 1 0 0 0 0 1 #3 1 0 1 1 0...

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,recursion,binary-tree,combinations

Building on ideas above....Here is python generator code to produce all equivalent orderings. import collections Node = collections.namedtuple('Node', ('root','left', 'right')) def tree_from_list(lst): if not lst: return None root = lst[0] left_lst = [x for x in lst if x > root] right_lst = [x for x in lst if x...

With itertools.product: In [1]: from itertools import product In [2]: list(product((0, 1), repeat=4)) Out[2]: [(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0), (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0),...

performance,matlab,matrix,combinations,combinatorics

To replace nchoosek(1:N,2) With bsxfun - [Y,X] = find(bsxfun(@gt,[1:N]',[1:N])) pair = [X, Y]; With tril and find only (without ind2sub) - [y,x] = find(tril(true(N),-1)) pair = [X, Y]; ...

java,algorithm,combinations,combinatorics

1.) k-permutation of n without repetion: http://www.statlect.com/comdis1.htm 2.) It depends on which you are searching for. For example, I offer you genetic algorithms which can find the best candidate based on a special heuristic if you can order a "goodness degree" to the possible solutions....

php,algorithm,numbers,combinations,letter

This should work for you: Basically I have an array with all letters ([A-Z]) and an array with all numbers ([0-9]). Then you define which order of possible characters you want. E.g. here you want letterNumber, letterNumber and then the third spot only number. After this you loop through everything...

What you have posted as a formula is nothing but Combination. It says that k-combination from a set of n elements is given by nCk OR n! / (k!*(n-k)!). Next, the number of combinations of n different things taken m at a time, when k particular objects occur is n-mCk-m...

sql-server,data-structures,combinations

This can be done by a simple update statement: Update table Set colC = colC + char(13) + char(10) + colD +char(13) + char(10) + colE Note that char(13) + char(10) is a line break. After you verify that the data was copied, use alter table to drop colD and...

batch-file,combinations,permutation,batch-processing

Now Tested: @echo off set "file1=fileA.txt" set "file2=fileB.txt" set "file3=fileC.txt" break>"%file3%" for /f "useback tokens=* delims=" %%# in ("%file1%") do ( for /f "useback tokens=* delims=" %%$ in ("%file2%") do ( echo %%#%%$>>"%file3%" ) ) ...

pairs xs = [[x1, x2] | (x1:xs1) <- tails xs, x2 <- xs1] ...assuming the list starts out unique, or you could compose this with nub otherwise....

performance,matlab,combinations

You can also use the factorial function and compute nchoosek manually. Recall the formula for nchoosek: As such, we can use factorial to help in this computation, which also accepts arrays and matrices of any shape. Therefore, your code would simply be: y = factorial(x) ./ (factorial(3) .* factorial(x-3)); Given...

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'] ...

java,algorithm,math,combinations

you can get all possible combinations with this code for ( int i = 98; i > 0; i-- ) { for ( int j = 1; j+i < 100; j++ ) { int k = 100 - i - j; //do stuff with i,j,k } } ...

Your logic is completely wrong and you are way complexifying what you are looking for. It s much simpler than you think. First: in order to drastically speed up your script and queries as well as protecting it from any attacks, use PDO prepared statements and security protocols. Mysql none...

You can try c(outer(a, b, FUN=paste0)) #[1] "2013-03-31" "2014-03-31" "2015-03-31" "2013-06-30" "2014-06-30" #[6] "2015-06-30" Or do.call(paste0,expand.grid(a,b)) Or sprintf('%s%s', rep(a, length(b)), rep(b, length(a))) ...

java,combinations,combinatorics

This can be easily done without recursion. The idea is to have array of size k (length of subsequence), which at every moment keeps sequence of indices of elements in the input array. On every iteration, try to generate new index sequence if this is possible. First index sequence will...

Here's a way with list comprehension: >>> lst = [6, 7, 8, 9] >>> [lst[i:j] for j in range(len(lst)+1) for i in range(j)] [[6], [6, 7], [7], [6, 7, 8], [7, 8], [8], [6, 7, 8, 9], [7, 8, 9], [8, 9], [9]] Or if you value the order and...

r,functional-programming,combinations

This looks like a job for the reval package! First, generate the parameter sets (see Generating all distinct permutations of a list in R and data.frame rows to a list): all <- expand.grid(0:2, 0:2, 0:2, stringsAsFactors = FALSE) perms <- all[apply(all, 1, function(x) {length(unique(x)) == 3}),] orders <- as.list(as.data.frame(t(perms))) names(orders)...

You can use Map to loop over the list elements and then use rbind: do.call(rbind, Map(expand.grid, l1, l2)) # Var1 Var2 #1 a e #2 b e #3 c e #4 a f #5 b f #6 c f #7 d g #8 d h #9 d i Map is...

This is my first Stack Overflow answer: This might not be the most elegant approach, but it works. First eliminate any repetitions in the data. My inclination is to use a VBScript dictionary for that -- but you can do it in pure VBA like this. If you have n...

A slightly faster version of Marat's answer: f.roland <- function(n, m) { ind <- combn(seq_len(n), m) ind <- t(ind) + (seq_len(ncol(ind)) - 1) * n res <- rep(0, nrow(ind) * n) res[ind] <- 1 matrix(res, ncol = n, nrow = nrow(ind), byrow = TRUE) } all.equal(f.2(16, 8), f.roland(16, 8)) #[1]...

A good start is to do: x1 <- cuchars x2 <- sprintf("'X' as %s", cuchars) expand.grid(Map(c, x1, x2)) # E F G # 1 E F G # 2 'X' as E F G # 3 E 'X' as F G # 4 'X' as E 'X' as F G...

You can calculate it by the memoization nCr = (n-1)Cr + (n-1)C(r-1) for M<=5000. You can visit the link for more info http://discuss.codechef.com/questions/3869/best-known-algos-for-calculating-ncr-m

algorithm,recursion,combinations

Let's say B is number of bins and O is number of objects. The algorithm should just count in base-B (as opposed to base-10 or base-2), counting from 0B to AA...AAB, where A = B - 1, and number of digits equals O. The easiest way to count in base-B...

Here is a dynamic-programming example: def make_combo_dict(nums, max_): nums = sorted(set(nums)) prev = {0: [""]} # base state: no combinations for num in nums: nxt = defaultdict(list) for total, ways in prev.items(): # k = 0 nxt[total] = ways # k > 0 max_k = (max_ - total) // num...

java,recursion,garbage-collection,iteration,combinations

Did the same algorithm using math combination by the lib (Combinatoricslib) Here is the code, it use alot less memory, but stills takes long because use brute force, trying all possible combination and filtering the ones the match the rules. You'll need java 8 to compile this, check if suits...

This is a simple state search problem. You have a starting state, and you can expand it (create its children) following some criteria. In your case, by decrementing one of the values, but not below some lower bound. If you're not familiar with DFS or BFS, I suggest reading on...

Given 3 numbers, you can tell if they are divisible by 3 using the modulus operator: List<int> numbers = new List<int> {4, 8, 11}; // Represents three random cards // This will be set to true if the sum of the numbers is evenly divisible by 3 bool numbersAreDivisibleByThree =...

algorithm,combinations,dynamic-programming

This is one solution: items = [1,1,3,4,5] knapsack = [] limit = 7 def print_solutions(current_item, knapsack, current_sum): #if all items have been processed print the solution and return: if current_item == len(items): print knapsack return #don't take the current item and go check others print_solutions(current_item + 1, list(knapsack), current_sum) #take...

You want cartesian product, not combinations. import itertools print list(itertools.product([1, 2, 3], repeat=3)) ...

java,boolean,expression,combinations

This certainly does not need an exhaustive search. You can reason as follows: Due to the || !r you know that the 4 combinations with r == false satisfy the expression Due to the || q you know that of the remaining 4 combinations, the 2 with q == true...

matlab,vector,combinations,cartesian-product

a = [1 2 3] a = 1 2 3 >> b = [4 5 6] b = 4 5 6 >> c=allcomb(a,b)' c = 1 1 1 2 2 2 3 3 3 4 5 6 4 5 6 4 5 6 You can find the allcomb function here...

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.

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])))...

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...

I guess you could create your own helper function, something like that MyList <- function(n) expand.grid(lapply(paste0("A", seq_len(n)), c, "No")) Then simply pass it the number of elements (e.g., 3) MyList(3) # Var1 Var2 Var3 # 1 A1 A2 A3 # 2 No A2 A3 # 3 A1 No A3 #...

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,...

javascript,arrays,algorithm,collections,combinations

The condition for the nested for is incorrect. Change it from j > 0 to j > i, and it will work fine: function getSubs(arr){ var newarr = []; for (var i=0;i<arr.length;i++){ for (var j=arr.length;j>i;j--){ newarr.push(arr.slice(i,j)); } } return newarr; } Input: [1,2,3] Output: [[1,2,3],[1,2],[1],[2,3],[2],[3]] Just to note: considering Array.slice(initialOffset,...

You could use the itertools.product function, which takes a list of iterators and creates the iterator of their cartesian product (see documentation). In my solution I use the values from the parameter dictionary as the iterators. I go over the product of the options for each key (for values_option in...

You must rather use: do.call(expand.grid, split(myMatrix, rep(1:nrow(myMatrix), ncol(myMatrix)))) # 1 2 #1 1 4 #2 2 4 #3 3 4 #4 1 5 #5 2 5 #6 3 5 #7 1 6 #8 2 6 #9 3 6 ...

You keep asking questions very closely related, and getting answers for them, you should try to connect all the bits by yourself. In this case, start with the excellent answer from Horchler, inject this result in the (just as excellent) answer from Luis Mendo to get all possible combinations (which...

algorithm,recursion,combinations,subset

I think this can help you: void subset(vector<int> &input, vector<int> output, int current) { static int n=0; if (current == input.size()) { cout<<n++<<":\t {"; for(int i=0;i<output.size();i++) cout<<output[i]<<", "; cout<<"\b\b}\n"; } else { subset(input, output, current+1); //exclude current'th item output.push_back(input[current]); subset(input, output, current+1); //include current'th item } } and first time...

mysql,database,combinations,auto-increment

I'll try to answer your question to the point where I explain what's going on. First off, the feature you want is available in MyISAM storage engine (kind of, there's a twist). However, transactions and referential integrity aren't available. Now for auto_increment - it gives unique values to rows. However,...

You can use something like this: string _combinations = String.Empty; for (int i=0; i<arr.Length;i++){ for (int j=0; j<arr.Length;j++){ for (int k=0; k<arr.Length;k++){ combinations=String.Concat(combinations,arr[i], arr[j], arr[k], ","); } } } In case there are too many items in array, then make a recursive function call, adding chars from next array's item...

java,python,c,algorithm,combinations

Here's a suggestion: Organise your data so that it is a list of lists: The main list represents the groups, the sublists represent the subjects in each group. subjects = [ ["History", "Sociology", "Economics"], ["Bengali", "Hindi"], ["Sanskrit", "Mathematics"], ["Philosophy"], ["Political Science"], ["English"] ] Then proceed in three nested steps: First,...

This would return combinations of sizes 4 to 1 and remove the non-PAL items from any that have PAL in them. It uses the combn function which returns combination-sets of a particular size: lapply( lapply(1:4 , combn, x=strings), # modify if smaller set of sizes needed function(cx){ apply(cx, 2, function(col)...

▶ a1 = [11,12,13] #⇒ [11, 12, 13] ▶ b1 = [21,22,23] #⇒ [21, 22, 23] ▶ a1.zip(b1).reduce(&:product).map(&:flatten) #⇒ [[11, 12, 13], [11, 12, 23], [11, 22, 13], [11, 22, 23], #⇒ [21, 12, 13], [21, 12, 23], [21, 22, 13], [21, 22, 23]] ▶ a1.zip(b1).reduce(&:product).map(&:flatten).map { |e| e.reduce &:+...

See if this works for you - threshold = 4; A = 0:threshold A1 = allcomb(A,A,A,A) %// Or use: A1 = combvec(A,A,A,A).' from Neural Network Toolbox combs = A1(sum(A1.^2,2)<=threshold,:) Please note that the code listed above uses allcomb from MATLAB File-exchange. Output - combs = 0 0 0 0 0...

This problem seems to be equivalent to the set cover problem.

You must use BigInteger for the computation of factorials up to around 1000. public static BigInteger fact(long j){ BigInteger prod = BigInteger.ONE; for(long i = j; i > 0; i--){ BigInteger f = BigInteger.valueOf( i ); prod = prod.multiply( f ); } return prod; } ...

Here is my suggestion for a script: <?php $array1 = array("a","b","c","d"); $array2 = array("h","g","f","e"); // produce 8-byte-string with each 4 values of array 1 and 2 // looks like a byte with 8 bits of value 0 and 1 // and delete combinations with other than 4 zeroes and 4...

Tap Alt+F11 and when the VBE opens, immediately use the pull-down menus to Insert ► Module (Alt+I,M). Paste the following into the new pane titled something like Book1 - Module1 (Code), Sub name_by_name() Dim i As Long, j As Long, lr As Long With ActiveSheet lr = .Cells(Rows.Count, 1).End(xlUp).Row For...

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..)...

python,numpy,combinations,sympy,itertools

Assuming I understand your aim (not sure what you might want to happen in cases of duplicate elements, namely whether you want to consider them distinct or not), you could use itertools.product: import itertools def everywhere(seq, width): for locs in itertools.product(range(width), repeat=len(seq)): output = [[] for _ in range(width)] for...

python,list,combinations,dynamically-generated

That's what itertools.product is for: >>> lst = ['ab','cd','f'] >>> from itertools import product >>> list(product(*lst)) [('a', 'c', 'f'), ('a', 'd', 'f'), ('b', 'c', 'f'), ('b', 'd', 'f')] ...

java,functional-programming,java-8,combinations

This is an algorithm that I wrote for solving some Euler Project problems : public static <E> Stream<List<E>> combinations(List<E> l, int size) { if (size == 0) { return Stream.of(Collections.emptyList()); } else { return IntStream.range(0, l.size()).boxed(). <List<E>> flatMap(i -> combinations(l.subList(i+1, l.size()), size - 1).map(t -> pipe(l.get(i), t))); } } private...

matlab,matrix,vector,combinations,vectorization

You can generate all possible binary combinations to determine the matrix you want: a = [1 2 3]; n = size(a,2); % generate bit combinations c =(dec2bin(0:(2^n)-1)=='1'); % remove first line c = c(2:end,:) n_c = size(c,1); a_rep = repmat(a,n_c,1); result = c .* a_rep Output: c = 0 0...

sample to fix void com(int *a, int *t, int len, int i){ if(i == len){ for(int k = 0; k < len; k++) printf("%d ", t[k]); printf("\n"); return; } while(*a){ t[i] = *a; com(++a, t, len, i+1); } } int main(void){ int t[3]; com((int[]){1,2,3,4, 0}, t, 3, 0); // ^end...

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...

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),...

In a recursive query the terms in the search table that are used in an iteration are removed and then the query repeats with the remaining records. In your case that means that as soon as you have processed the first array element ("A") it is no longer available for...

java,windows,events,combinations,keyevent

Possibly this has something to do with key rollover: https://en.wikipedia.org/wiki/Rollover_(key) Some keyboards give special connections to the WASD keys as they are used frequently in gaming.

ORIGINAL WORDING (SKIP TO THE UPDATE BELOW) Let's assume that the n elements are the integers 1..n. Represent every k-combination in increasing order (this representation gets rid of permutations inside the k-combination.) Now consider the lexicographic order between k-combinations (of n elements). In other words, {i_1..i_k} < {j_1..j_k} if there...

c#,list,combinations,cartesian-product,cartesian

As long as you only want to create the cartesian product of two sets you can use LINQ SelectMany: var n = 2; var numbers = Enumerable.Range(0, n + 1); var cartesianProduct = numbers.SelectMany(_ => numbers, (a, b) => Tuple.Create(a, b)); When cartesianProduct is enumerated it will generate 9 tuples...

The process which turns something like [['a','b'], ['c'], ['d', 'e', 'f'], ['g', 'h'], ['k'], ['l']] into the sequence [['a','c','d','g','k','l'], ['a','c','d','h','k','l'], ... is called taking the Cartesian product. I don't think there's a name for the specific process of also concatenating the result when they're strings. (Also note that I've made...

You can use this solution: col.i <- do.call(c,lapply(1:3,combn,x=5,simplify=F)) # [[1]] # [1] 1 # # [[2]] # [1] 2 # # <...skipped...> # # [[24]] # [1] 2 4 5 # # [[25]] # [1] 3 4 5 Here, col.i is a list every element of which contains column indices....

javascript,events,click,combinations,keypress

As I commented above, the click event does not have a property called keyCode so doing event.keyCode will not work. The only reason that control and alt work is because they are properties of the click event, event.ctrlKey and event.altKey. You can be a little more creative and use something...

The solution below will flatten and product any combination of arrays and scalars: a = [["1a","1b"],2,3,["4a","4b"]] a.combination(a.size - 1).map do |e| e.map { |scalar| [*scalar] } # convert scalars to arrays of size 1 end.map do |arrays| arrays.reduce &:product # reduce by vector/cartesian product end.flat_map do |deeps| deeps.map &:flatten #...

So I found a way to get your combinations. You should really have given an more minimal example to explain your problem (that's how I solved it by the way). The procedure is: Get all the {2 element} unique combination for each set. Then build an index of the result...

python,math,combinations,itertools

Always there are 2n−1 non-empty subsets of the set {1,...,n}. For example consider the list ['a','b','c']: >>> [list(combinations(['a','b','c'],i)) for i in range(1,4)] [[('a',), ('b',), ('c',)], [('a', 'b'), ('a', 'c'), ('b', 'c')], [('a', 'b', 'c')]] >>> l=[list(combinations(['a','b','c'],i)) for i in range(1,4)] >>> sum(map(len,l)) 7 That the length of our list is...

postgresql,unique,combinations

A variation on Neil's solution which doesn't need an extension is: create table friendz ( from_id int, to_id int ); create unique index ifriendz on friendz(greatest(from_id,to_id), least(from_id,to_id)); Neil's solution lets you use an arbitrary number of columns though. We're both relying on using expressions to build the index which is...

python,string,combinations,variations

Write a recursive function that takes a substring of the input. This function then examines all rules. For each rule that matches, one replacement is done, and the remainder of the string is processed by a recursive call: def apply_rules(rules, input, start=0): # First yield the outcome of no applied...

# 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,]) ...

python,string,set,combinations

import itertools permut = set() permut.add("D") permut.add("C") def getAllKombos(stuff): returnvalue = set() for L in range(0, len(stuff) + 1): for subset in itertools.permutations(stuff, L): for i in subset: x = x + (str(i)) returnvalue.add(x) x = "" return returnvalue print getAllKombos(permut) This code now works, all you had to do...

sql,ms-access,combinations,distinct-values

Try this query: SELECT ColumnA FROM table t GROUP BY ColumnA HAVING COUNT(DISTINCT ColumnB) >= 2; An alternative HAVING clause that might be more efficient is: HAVING MIN(ColumnB) <> MAX(ColumnB) ...

One way you can do this: Use two nested loops to multiply each number in the list with each other number, then recurse on that new list. This is not very efficient, as you will have tons of duplicate function calls (e.g. for multiplying the 3 in (3, 2, 2,...

Here's a simple function that will take a permutation of k ones and n-k zeros and return the next combination of nchoosek. It's completely independent of the values of n and k, taking the values directly from the input array. function [nextc] = nextComb(oldc) nextc = []; o = find(oldc,...