Questions tagged [combinatorics]
Deals with combinations of entities belonging to a finite set in accordance with certain constraints.
combinatorics
2,360
questions
853
votes
41
answers
1.1m
views
How do I generate all permutations of a list?
How do I generate all the permutations of a list? For example:
permutations([])
[]
permutations([1])
[1]
permutations([1, 2])
[1, 2]
[2, 1]
permutations([1, 2, 3])
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, ...
283
votes
11
answers
325k
views
How can I match up permutations of a long list with a shorter list (according to the length of the shorter list)? [duplicate]
I’m having trouble wrapping my head around a algorithm I’m try to implement. I have two lists and want to take particular combinations from the two lists.
Here’s an example.
names = ['a', 'b']
numbers ...
166
votes
36
answers
214k
views
Generate list of all possible permutations of a string
How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters.
Any language would work, but it should ...
138
votes
6
answers
124k
views
How can I get "permutations with repetitions/replacement" from a list (Cartesian product of a list with itself)?
Suppose I have a list die_faces = [1, 2, 3, 4, 5, 6]. I want to generate all 36 possible results for rolling two dice: (1, 1), (1, 2), (2, 1) etc. If I try using permutations from the itertools ...
128
votes
13
answers
48k
views
Fast permutation -> number -> permutation mapping algorithms
I have n elements. For the sake of an example, let's say, 7 elements, 1234567. I know there are 7! = 5040 permutations possible of these 7 elements.
I want a fast algorithm comprising two functions:...
91
votes
4
answers
30k
views
Cartesian product of a dictionary of lists
I'm trying to write some code to test out the Cartesian product of a bunch of input parameters.
I've looked at itertools, but its product function is not exactly what I want. Is there a simple ...
88
votes
12
answers
13k
views
Generate all permutations of a list without adjacent equal elements
When we sort a list, like
a = [1,2,3,3,2,2,1]
sorted(a) => [1, 1, 2, 2, 2, 3, 3]
equal elements are always adjacent in the resulting list.
How can I achieve the opposite task - shuffle the list ...
87
votes
6
answers
23k
views
Generating permutations lazily
I'm looking for an algorithm to generate permutations of a set in such a way that I could make a lazy list of them in Clojure. i.e. I'd like to iterate over a list of permutations where each ...
83
votes
16
answers
45k
views
Cartesian product of 2 lists in Haskell
I wish to produce the Cartesian product of 2 lists in Haskell, but I cannot work out how to do it. The cartesian product gives all combinations of the list elements:
xs = [1,2,3]
ys = [4,5,6]
...
72
votes
12
answers
51k
views
Generating all Possible Combinations
Given 2 arrays Array1 = {a,b,c...n} and Array2 = {10,20,15....x} how can I generate all possible combination as Strings a(i) b(j) c(k) n(p)
where
1 <= i <= 10, 1 <= j <= 20 , 1 <= k ...
70
votes
14
answers
210k
views
Creating all possible k combinations of n items in C++
There are n people numbered from 1 to n. I have to write a code which produces and print all different combinations of k people from these n. Please explain the algorithm used for that.
66
votes
17
answers
100k
views
Combinatoric 'N choose R' in java math?
Is there a built in method in a java library that can compute 'N choose R' for any N, R?
65
votes
34
answers
122k
views
How can I print out all possible letter combinations a given phone number can represent?
I just tried for my first programming interview and one of the questions was to write a program that given a 7 digit telephone number, could print all possible combinations of letters that each number ...
53
votes
10
answers
21k
views
Non-redundant version of expand.grid
The R function expand.grid returns all possible combination between the elements of supplied parameters. e.g.
> expand.grid(c("aa", "ab", "cc"), c("aa", "ab", "cc"))
Var1 Var2
1 aa aa
2 ab ...
53
votes
5
answers
30k
views
Set partitions in Python
I have an array of [1,2,3]
I want to make all the possible combinations using all elements of the array:
Result:
[[1], [2], [3]]
[[1,2], [3]]
[[1], [2,3]]
[[1,3], [2]]
[[1,2,3]]
52
votes
2
answers
11k
views
What does this list permutations implementation in Haskell exactly do?
I am studying the code in the Data.List module and can't exactly wrap my head around this implementation of permutations:
permutations :: [a] -> [[a]]
permutations xs0 = xs0 : ...
46
votes
7
answers
93k
views
How can I get pairs of values, where the first is taken from one list and the second from another list? [duplicate]
I want something like the code below, but in a "Pythonic" style or using the standard library:
def combinations(a,b):
for i in a:
for j in b:
yield(i,j)
46
votes
5
answers
12k
views
Google Interview: Arrangement of Blocks
You are given N blocks of height 1…N. In how many ways can you arrange these blocks in a row such that when viewed from left you see only L blocks (rest are hidden by taller blocks) and when seen from ...
44
votes
8
answers
4k
views
Random sample of character vector, without elements prefixing one another
Consider a character vector, pool, whose elements are (zero-padded) binary numbers with up to max_len digits.
max_len <- 4
pool <- unlist(lapply(seq_len(max_len), function(x)
do.call(paste0, ...
41
votes
12
answers
67k
views
Permutations - all possible sets of numbers
I have numbers, from 0 to 8. I would like in result, all possible sets of those numbers, each set should use all numbers, each number can occur only once in a set.
I would like to see solution made ...
40
votes
8
answers
41k
views
Get all permutations of a PHP array?
Given a PHP array of strings, e.g.:
['peter', 'paul', 'mary']
How to generate all possible permutations of elements of this array? i.e.:
peter-paul-mary
peter-mary-paul
paul-peter-mary
paul-mary-...
38
votes
11
answers
14k
views
Generating all 5 card poker hands
This problem sounds simple at first glance, but turns out to be a lot more complicated than it seems. It's got me stumped for the moment.
There are 52c5 = 2,598,960 ways to choose 5 cards from a 52 ...
37
votes
23
answers
8k
views
Code-golf: generate pascal's triangle
Generate a list of lists (or print, I don't mind) a Pascal's Triangle of size N with the least lines of code possible!
Here goes my attempt (118 characters in python 2.6 using a trick):
c,z,k=locals,...
34
votes
5
answers
31k
views
all permutations of a binary sequence x bits long
I would like to find a clean and clever way (in python) to find all permutations of strings of 1s and 0s x chars long. Ideally this would be fast and not require doing too many iterations...
So, for ...
34
votes
5
answers
52k
views
Generate all possible combinations of the elements of some vectors (Cartesian product)
I would like to generate all the possible combinations of the elements of a given number of vectors.
For example, for [1 2], [1 2] and [4 5] I want to generate the elements:
[1 1 4; 1 1 5; 1 2 4; 1 ...
34
votes
2
answers
90k
views
Algorithm to get all the combinations of size n from an array (Java)? [closed]
Right now I'm trying to write a function that takes an array and an integer n, and gives a list of each size n combination (so a list of int arrays). I am able to write it using n nested loops, but ...
32
votes
6
answers
3k
views
Secret Santa - Generating 'valid' permutations
My friends invited me home to play the game of Secret Santa, where we are supposed to draw a lot & play the role of 'Santa' for a friend in the group.
So, we write all our names and pick a name ...
31
votes
11
answers
26k
views
Calculating the Amount of Combinations
Cheers,
I know you can get the amount of combinations with the following formula (without repetition and order is not important):
// Choose r from n
n! / r!(n - r)!
However, I don't know how to ...
31
votes
10
answers
1k
views
Algorithm to determine all possible ways a group of values can be removed from a sequence
I'm trying to determine how many different ways I can remove a group of values from a sequence, leaving the original sequence in order (stable), and making sure to remove only 1 instance value each ...
31
votes
1
answer
1k
views
Is `scipy.misc.comb` faster than an ad-hoc binomial computation?
Is it conclusive that now the scipy.misc.comb is indeed faster than the ad-hoc implementation?
According to an old answer, Statistics: combinations in Python, this homebrew function is faster than ...
29
votes
9
answers
22k
views
How to design an algorithm to calculate countdown style maths number puzzle
I have always wanted to do this but every time I start thinking about the problem it blows my mind because of its exponential nature.
The problem solver I want to be able to understand and code is ...
28
votes
5
answers
29k
views
Scheduling algorithm for a round-robin tournament?
I recently did studying stuff and meet up with Donald Knuth. But i didn't found the right algorithm to my problem.
The Problem We have a league with n players. every week they have a match with one ...
28
votes
2
answers
28k
views
Get all pairwise combinations from a list
For example, if the input list is
[1, 2, 3, 4]
I want the output to be
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]
If possible, I would like a solution which is better than the brute force ...
27
votes
9
answers
11k
views
Variable amount of nested for loops
Edit: I'm sorry, but I forgot to mention that I'll need the values of the counter variables. So making one loop isn't a solution I'm afraid.
I'm not sure if this is possible at all, but I would like ...
27
votes
6
answers
8k
views
Does Python have a function which computes multinomial coefficients?
I was looking for a Python library function which computes multinomial coefficients.
I could not find any such function in any of the standard libraries.
For binomial coefficients (of which ...
26
votes
4
answers
17k
views
N-D version of itertools.combinations in numpy
I would like to implement itertools.combinations for numpy. Based on this discussion, I have a function that works for 1D input:
def combs(a, r):
"""
Return successive r-length combinations ...
25
votes
2
answers
18k
views
What is the Julia function to count combinations (n choose k)?
I'm looking for the (hopefully built-in) function in Julia that calculates the number of combinations
I could obviously implement my own using factorials, but I'm almost certain somebody has ...
25
votes
5
answers
18k
views
all combinations of k elements out of n
Can somebody provide me a link or pseudocode of a function for finding all combinations of k elements out of n? possibly in STL. I don't need to compute n choose k, I need to list all vectors of ...
25
votes
6
answers
2k
views
Picking unordered combinations from pools with overlap
I have pools of values and I would like to generate every possible unordered combination by picking from certain pools.
For example, I wanted to pick from pool 0, pool 0, and pool 1:
>>> ...
25
votes
6
answers
2k
views
Find most efficient groups of pairs
Problem
I have a group of people, and I want each person to have a 1:1 meeting with every other person in the group. A given person can only meet with one other person at a time, so I want to do the ...
25
votes
6
answers
6k
views
Travelling salesman with repeat nodes & dynamic weights
Given a list of cities and the cost to fly between each city, I am trying to find the cheapest itinerary that visits all of these cities. I am currently using a MATLAB solution to find the cheapest ...
25
votes
3
answers
907
views
OEIS A002845: Number of distinct values taken by 2^2^...^2 (with n 2's and parentheses inserted in all possible ways)
I am looking for a reasonably fast algorithm to calculate terms of the OEIS sequence A002845. Let me restate its definition here.
Let ^ denote the exponentiation operator. Consider expressions of the ...
24
votes
2
answers
2k
views
Memory-constrained coin changing for numbers up to one billion
I faced this problem on one training. Namely we have given N different values (N<= 100). Let's name this array A[N], for this array A we are sure that we have 1 in the array and A[i] ≤ 109. ...
23
votes
6
answers
29k
views
Generate all combinations in SQL
I need to generate all combinations of size @k in a given set of size @n. Can someone please review the following SQL and determine first if the following logic is returning the expected results, and ...
23
votes
8
answers
98k
views
Number of combinations (N choose R) in C++
Here I try to write a program in C++ to find NCR. But I've got a problem in the result. It is not correct. Can you help me find what the mistake is in the program?
#include <iostream>
using ...
22
votes
5
answers
2k
views
Given a permutation's lexicographic number, is it possible to get any item in it in O(1)
I want to know whether the task explained below is even theoretically possible, and if so how I could do it.
You are given a space of N elements (i.e. all numbers between 0 and N-1.) Let's look at ...
21
votes
3
answers
27k
views
Getting all possible combinations from a list of numbers
I'm looking for an efficient way to achieve this:
you have a list of numbers 1.....n (typically: 1..5 or 1..7 or so - reasonably small, but can vary from case to case)
you need all combinations of ...
21
votes
2
answers
2k
views
How to get all mappings between two lists?
We have two lists, A and B:
A = ['a','b','c']
B = [1, 2]
Is there a pythonic way to build the set of all maps between A and B containing 2^n (here 2^3=8)? That is:
[(a,1), (b,1), (c,1)]
[(a,1), (b,...
21
votes
5
answers
20k
views
Number of n-element permutations with exactly k inversions
I am trying to efficiently solve SPOJ Problem 64: Permutations.
Let A = [a1,a2,...,an] be a permutation of integers 1,2,...,n. A pair
of indices (i,j), 1<=i<=j<=n, is an inversion of the ...
21
votes
5
answers
13k
views
Finding all the unique permutations of a string without generating duplicates
Finding all the permutations of a string is by a well known Steinhaus–Johnson–Trotter algorithm. But if the string contains the repeated characters such as
AABB,
then the possible unique combinations ...