Advertisement
Guest User

Algorithm for computing partitions of a set of n elements in

a guest
Nov 7th, 2017
242
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var count = 0;
  2. var people = ["A","B","C","D","E","F"];
  3. var combinations = [];
  4. var partitions = [];
  5.  
  6. example();
  7. generate(people.splice(0), []);
  8. for (let i = 0; i < combinations.length; ++i)
  9. pretty_print(partitions[i]);
  10.  
  11. function pretty_print(v) {
  12.   var message = "combination no " + (++count) + ": [ ";
  13.   for (let i = 0; i < v.length; ++i) { message += v[i] + " "; }
  14.   message += "]";
  15.   alert(message);
  16. }
  17.  
  18. function go(combination, offset, k) {
  19.   if (k == 0) {
  20.     combinations.push(combination.slice(0));
  21.     return;
  22.   }
  23.   for (let i = offset; i <= people.length - k; ++i) {
  24.     combination.push(people[i]);
  25.     go(combination, i+1, k-1);
  26.     combination.pop();
  27.   }
  28. }
  29.  
  30. function example() {
  31.   var k = 3;
  32.  
  33.   go([], 0, k);
  34. }
  35.  
  36. function generate(people, partition)
  37. {
  38.     if (people.length == 0)
  39.     {
  40.         partitions.push(partition.splice(0));
  41.         return;
  42.     }
  43.    
  44.     for (let i = 0; i < combinations.length; ++i)
  45.     {
  46.         var combination = combinations[i];
  47.         partition.push(combination);
  48.         var peopleCopy = people.splice(0);
  49.         for (let j = 0; j < combination.length; ++j)
  50.         {
  51.             peopleCopy.splice(peopleCopy.indexOf(combination[j]), 1);
  52.         }
  53.         generate(peopleCopy, partition);
  54.         for (let j = 0; j < combination.length; ++j)
  55.         {
  56.             partition.splice(partition.indexOf(combination[j]), 1);
  57.         }
  58.     }
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement