Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- (* this will find the [x] combination of a [set] list when taking [k] elements *)
- let combination_maccaffery set k x =
- (* maximize function -- maximize a that is aCb *)
- (* return largest c where c < i and choose(c,i) <= z *)
- let rec maximize a b x =
- if (choose a b ) <= x then a else maximize (a-1) b x
- in
- let rec iterate n x i = match i with
- | 0 -> []
- | i ->
- let max = maximize n i x in
- max :: iterate n (x - (choose max i)) (i-1)
- in
- if x < 0 then failwith "errors" else
- let idxs = iterate (List.length set) x k in
- List.map (List.nth set) (List.sort (-) idxs)
- being
- being
- public static IEnumerable<IEnumerable<T>> Combinations<T>(this IEnumerable<T> elements, int k)
- {
- return k == 0 ? new[] { new T[0] } :
- elements.SelectMany((e, i) =>
- elements.Skip(i + 1).Combinations(k - 1).Select(c => (new[] {e}).Concat(c)));
- }
- var result = Combinations(new[] { 1, 2, 3, 4, 5 }, 3);
- 123
- 124
- 125
- 134
- 135
- 145
- 234
- 235
- 245
- 345
- void print_combinations(const char *string)
- {
- int i, j, k;
- int len = strlen(string);
- for (i = 0; i < len - 2; i++)
- {
- for (j = i + 1; j < len - 1; j++)
- {
- for (k = j + 1; k < len; k++)
- printf("%c%c%cn", string[i], string[j], string[k]);
- }
- }
- }
- void print_combinations(const char *string)
- {
- int i, j, k;
- int len = strlen(string);
- for (i = 0; i < len - 2; i++)
- {
- for (j = i + 1; j < len - 1; j++)
- {
- for (k = j + 1; k < len; k++)
- printf("%c%c%cn", string[i], string[j], string[k]);
- }
- }
- }
- void print_combinations(const char *string)
- {
- int i, j, k;
- int len = strlen(string);
- for (i = 0; i < len - 2; i++)
- {
- for (j = i + 1; j < len - 1; j++)
- {
- for (k = j + 1; k < len; k++)
- printf("%c%c%cn", string[i], string[j], string[k]);
- }
- }
- }
- void print_combinations(const char *string)
- {
- int i, j, k;
- int len = strlen(string);
- for (i = 0; i < len - 2; i++)
- {
- for (j = i + 1; j < len - 1; j++)
- {
- for (k = j + 1; k < len; k++)
- printf("%c%c%cn", string[i], string[j], string[k]);
- }
- }
- }
- void print_combinations(const char *string)
- {
- int i, j, k;
- int len = strlen(string);
- for (i = 0; i < len - 2; i++)
- {
- for (j = i + 1; j < len - 1; j++)
- {
- for (k = j + 1; k < len; k++)
- printf("%c%c%cn", string[i], string[j], string[k]);
- }
- }
- }
- static IEnumerable<string> Combinations(List<string> characters, int length)
- {
- for (int i = 0; i < characters.Count; i++)
- {
- // only want 1 character, just return this one
- if (length == 1)
- yield return characters[i];
- // want more than one character, return this one plus all combinations one shorter
- // only use characters after the current one for the rest of the combinations
- else
- foreach (string next in Combinations(characters.GetRange(i + 1, characters.Count - (i + 1)), length - 1))
- yield return characters[i] + next;
- }
- }
- def choose_iter(elements, length):
- for i in xrange(len(elements)):
- if length == 1:
- yield (elements[i],)
- else:
- for next in choose_iter(elements[i+1:len(elements)], length-1):
- yield (elements[i],) + next
- def choose(l, k):
- return list(choose_iter(l, k))
- >>> len(list(choose_iter("abcdefgh",3)))
- 56
- def missing(miss,src):
- "Returns the list of items in src not present in miss"
- return [i for i in src if i not in miss]
- def permutation_gen(n,l):
- "Generates all the permutations of n items of the l list"
- for i in l:
- if n<=1: yield [i]
- r = [i]
- for j in permutation_gen(n-1,missing([i],l)): yield r+j
- n<len(l)
- for comb in permutation_gen(3,list("ABCDEFGH")):
- print comb
- object P26 {
- def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] =
- ls match {
- case Nil => Nil
- case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
- }
- def combinations[A](n: Int, ls: List[A]): List[List[A]] =
- if (n == 0) List(Nil)
- else flatMapSublists(ls) { sl =>
- combinations(n - 1, sl.tail) map {sl.head :: _}
- }
- }
- SELECT A.Letter, B.Letter, C.Letter
- FROM Alphabet AS A, Alphabet AS B, Alphabet AS C
- WHERE A.Letter<>B.Letter AND A.Letter<>C.Letter AND B.Letter<>C.Letter
- AND A.Letter<B.Letter AND B.Letter<C.Letter
- SELECT * FROM dbo.fn_GetMChooseNCombos('ABCD', 2, '')
- Word
- ----
- AB
- AC
- AD
- BC
- BD
- CD
- (6 row(s) affected)
- // author: Sourabh Bhat ([email protected])
- public class Testing
- {
- public static void main(String[] args)
- {
- // Test case num = 5, outOf = 8.
- int num = 5;
- int outOf = 8;
- int[][] combinations = getCombinations(num, outOf);
- for (int i = 0; i < combinations.length; i++)
- {
- for (int j = 0; j < combinations[i].length; j++)
- {
- System.out.print(combinations[i][j] + " ");
- }
- System.out.println();
- }
- }
- private static int[][] getCombinations(int num, int outOf)
- {
- int possibilities = get_nCr(outOf, num);
- int[][] combinations = new int[possibilities][num];
- int arrayPointer = 0;
- int[] counter = new int[num];
- for (int i = 0; i < num; i++)
- {
- counter[i] = i;
- }
- breakLoop: while (true)
- {
- // Initializing part
- for (int i = 1; i < num; i++)
- {
- if (counter[i] >= outOf - (num - 1 - i))
- counter[i] = counter[i - 1] + 1;
- }
- // Testing part
- for (int i = 0; i < num; i++)
- {
- if (counter[i] < outOf)
- {
- continue;
- } else
- {
- break breakLoop;
- }
- }
- // Innermost part
- combinations[arrayPointer] = counter.clone();
- arrayPointer++;
- // Incrementing part
- counter[num - 1]++;
- for (int i = num - 1; i >= 1; i--)
- {
- if (counter[i] >= outOf - (num - 1 - i))
- counter[i - 1]++;
- }
- }
- return combinations;
- }
- private static int get_nCr(int n, int r)
- {
- if(r > n)
- {
- throw new ArithmeticException("r is greater then n");
- }
- long numerator = 1;
- long denominator = 1;
- for (int i = n; i >= r + 1; i--)
- {
- numerator *= i;
- }
- for (int i = 2; i <= n - r; i++)
- {
- denominator *= i;
- }
- return (int) (numerator / denominator);
- }
- }
- m=(rand()%n)+1; // m will vary from 1 to n
- for (i=0;i<n;i++) a[i]=i+1;
- // we want to print all possible C(n,m) combinations of selecting m objects out of n
- printf("Printing C(%d,%d) possible combinations ...n", n,m);
- // This is an adhoc algo that keeps m pointers to the next valid combination
- for (i=0;i<m;i++) p[i]=i; // the p[.] contain indices to the a vector whose elements constitute next combination
- done=false;
- while (!done)
- {
- // print combination
- for (i=0;i<m;i++) printf("%2d ", a[p[i]]);
- printf("n");
- // update combination
- // method: start with p[m-1]. try to increment it. if it is already at the end, then try moving p[m-2] ahead.
- // if this is possible, then reset p[m-1] to 1 more than (the new) p[m-2].
- // if p[m-2] can not also be moved, then try p[m-3]. move that ahead. then reset p[m-2] and p[m-1].
- // repeat all the way down to p[0]. if p[0] can not also be moved, then we have generated all combinations.
- j=m-1;
- i=1;
- move_found=false;
- while ((j>=0) && !move_found)
- {
- if (p[j]<(n-i))
- {
- move_found=true;
- p[j]++; // point p[j] to next index
- for (k=j+1;k<m;k++)
- {
- p[k]=p[j]+(k-j);
- }
- }
- else
- {
- j--;
- i++;
- }
- }
- if (!move_found) done=true;
- }
- static bool nextCombination(int[] num, int n, int k)
- {
- bool finished, changed;
- changed = finished = false;
- if (k > 0)
- {
- for (int i = k - 1; !finished && !changed; i--)
- {
- if (num[i] < (n - 1) - (k - 1) + i)
- {
- num[i]++;
- if (i < k - 1)
- {
- for (int j = i + 1; j < k; j++)
- {
- num[j] = num[j - 1] + 1;
- }
- }
- changed = true;
- }
- finished = (i == 0);
- }
- }
- return changed;
- }
- static IEnumerable Combinations<T>(IEnumerable<T> elements, int k)
- {
- T[] elem = elements.ToArray();
- int size = elem.Length;
- if (k <= size)
- {
- int[] numbers = new int[k];
- for (int i = 0; i < k; i++)
- {
- numbers[i] = i;
- }
- do
- {
- yield return numbers.Select(n => elem[n]);
- }
- while (nextCombination(numbers, size, k));
- }
- }
- static void Main(string[] args)
- {
- int k = 3;
- var t = new[] { "dog", "cat", "mouse", "zebra"};
- foreach (IEnumerable<string> i in Combinations(t, k))
- {
- Console.WriteLine(string.Join(",", i));
- }
- }
- #include <vector>
- #include <stdexcept>
- template <typename Fci> // Fci - forward const iterator
- std::vector<std::vector<Fci> >
- enumerate_combinations(Fci begin, Fci end, unsigned int combination_size)
- {
- if(begin == end && combination_size > 0u)
- throw std::invalid_argument("empty set and positive combination size!");
- std::vector<std::vector<Fci> > result; // empty set of combinations
- if(combination_size == 0u) return result; // there is exactly one combination of
- // size 0 - emty set
- std::vector<Fci> current_combination;
- current_combination.reserve(combination_size + 1u); // I reserve one aditional slot
- // in my vector to store
- // the end sentinel there.
- // The code is cleaner thanks to that
- for(unsigned int i = 0u; i < combination_size && begin != end; ++i, ++begin)
- {
- current_combination.push_back(begin); // Construction of the first combination
- }
- // Since I assume the itarators support only incrementing, I have to iterate over
- // the set to get its size, which is expensive. Here I had to itrate anyway to
- // produce the first cobination, so I use the loop to also check the size.
- if(current_combination.size() < combination_size)
- throw std::invalid_argument("combination size > set size!");
- result.push_back(current_combination); // Store the first combination in the results set
- current_combination.push_back(end); // Here I add mentioned earlier sentinel to
- // simplyfy rest of the code. If I did it
- // earlier, previous statement would get ugly.
- while(true)
- {
- unsigned int i = combination_size;
- Fci tmp; // Thanks to the sentinel I can find first
- do // iterator to change, simply by scaning
- { // from right to left and looking for the
- tmp = current_combination[--i]; // first "bubble". The fact, that it's
- ++tmp; // a forward iterator makes it ugly but I
- } // can't help it.
- while(i > 0u && tmp == current_combination[i + 1u]);
- // Here is probably my most obfuscated expression.
- // Loop above looks for a "bubble". If there is no "bubble", that means, that
- // current_combination is the last combination, Expression in the if statement
- // below evaluates to true and the function exits returning result.
- // If the "bubble" is found however, the ststement below has a sideeffect of
- // incrementing the first iterator to the left of the "bubble".
- if(++current_combination[i] == current_combination[i + 1u])
- return result;
- // Rest of the code sets posiotons of the rest of the iterstors
- // (if there are any), that are to the right of the incremented one,
- // to form next combination
- while(++i < combination_size)
- {
- current_combination[i] = current_combination[i - 1u];
- ++current_combination[i];
- }
- // Below is the ugly side of using the sentinel. Well it had to haave some
- // disadvantage. Try without it.
- result.push_back(std::vector<Fci>(current_combination.begin(),
- current_combination.end() - 1));
- }
- }
- def combinations(list, k):
- """Choose combinations of list, choosing k elements(no repeats)"""
- if len(list) < k:
- return []
- else:
- seq = [i for i in range(k)]
- while seq:
- print [list[index] for index in seq]
- seq = get_next_combination(len(list), k, seq)
- def get_next_combination(num_elements, k, seq):
- index_to_move = find_index_to_move(num_elements, seq)
- if index_to_move == None:
- return None
- else:
- seq[index_to_move] += 1
- #for every element past this sequence, move it down
- for i, elem in enumerate(seq[(index_to_move+1):]):
- seq[i + 1 + index_to_move] = seq[index_to_move] + i + 1
- return seq
- def find_index_to_move(num_elements, seq):
- """Tells which index should be moved"""
- for rev_index, elem in enumerate(reversed(seq)):
- if elem < (num_elements - rev_index - 1):
- return len(seq) - rev_index - 1
- return None
- (defmacro txaat (some-list taken-at-a-time)
- (let* ((vars (reverse (truncate-list '(a b c d e f g h i j) taken-at-a-time))))
- `(
- ,@(loop for i below taken-at-a-time
- for j in vars
- with nested = nil
- finally (return nested)
- do
- (setf
- nested
- `(loop for ,j from
- ,(if (< i (1- (length vars)))
- `(1+ ,(nth (1+ i) vars))
- 0)
- below (- (length ,some-list) ,i)
- ,@(if (equal i 0)
- `(collect
- (list
- ,@(loop for k from (1- taken-at-a-time) downto 0
- append `((nth ,(nth k vars) ,some-list)))))
- `(append ,nested))))))))
- CL-USER> (macroexpand-1 '(txaat '(a b c d) 1))
- (LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 1)
- COLLECT (LIST (NTH A '(A B C D))))
- T
- CL-USER> (macroexpand-1 '(txaat '(a b c d) 2))
- (LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 2)
- APPEND (LOOP FOR B FROM (1+ A) TO (- (LENGTH '(A B C D)) 1)
- COLLECT (LIST (NTH A '(A B C D)) (NTH B '(A B C D)))))
- T
- CL-USER> (macroexpand-1 '(txaat '(a b c d) 3))
- (LOOP FOR A FROM 0 TO (- (LENGTH '(A B C D)) 3)
- APPEND (LOOP FOR B FROM (1+ A) TO (- (LENGTH '(A B C D)) 2)
- APPEND (LOOP FOR C FROM (1+ B) TO (- (LENGTH '(A B C D)) 1)
- COLLECT (LIST (NTH A '(A B C D))
- (NTH B '(A B C D))
- (NTH C '(A B C D))))))
- T
- CL-USER>
- CL-USER> (txaat '(a b c d) 1)
- ((A) (B) (C) (D))
- CL-USER> (txaat '(a b c d) 2)
- ((A B) (A C) (A D) (B C) (B D) (C D))
- CL-USER> (txaat '(a b c d) 3)
- ((A B C) (A B D) (A C D) (B C D))
- CL-USER> (txaat '(a b c d) 4)
- ((A B C D))
- CL-USER> (txaat '(a b c d) 5)
- NIL
- CL-USER> (txaat '(a b c d) 0)
- NIL
- CL-USER>
Add Comment
Please, Sign In to add comment