Creating all subsets recursively without using array












2














We get non negative integer number n from user and we must print all subsets of set ({1,2,3,...,n}). (n<=20)



for example for n=3 we must print:



{1 , 2 , 3}
{1 , 2}
{1 , 3}
{1}
{2 , 3}
{2}
{3}
{}


,s are optional and the sequence can be printed without any comma. (like {1 2 3})
I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. (lexicographical from the largest subset (the set itself) to null set)



I see a lot of codes in the Internet that solve this problem with arrays or using a bit array that indicate whether we use a number or not. The issue is that in this question, we are not allowed to use -any- type of array or other data structures like vector ,etc. Even using the array behaviour of something like string is completely prohibited. It must be solved only with recursion.



We are also not allowed to use any advanced functions. For example if we write it with C, we are allowed just to use stdio.h or for C++, only <iostream> is allowed and no other library.



I don't know how to do this without any arrays. How to check which number it must print and at the sametime, manage the {}.



PS1.
The question is simply generation powerset with these conditions:



USING ARRAY, STRING AND EVEN LOOPS ARE COMPLETELY PROHIBITED. JUST RECURSION.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.



PS2.



I write this code by help of George but it doesn't works fine. It doesn't have something like 1 2 4. It also repeats some cases.



#include <stdio.h>


void printAllSets (int size)
{printRows (size, 1);}

void printRows (int size , int start)
{
if (start<=size)
{printf( "{ ");
printRow (start, size);
printf ("}");
printf ("n");}
if (start <= size)
{printRows(size -1 , start);
printRows (size , (start + 1));}
}
printRow (int start, int limit)
{

if (start <= limit)
{

printf ("%d ",start);
printRow (start +1, limit);
}
}


int main()
{
printAllSets(5);
printf("{ }");
return 0;
}


PS3.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.










share|improve this question
























  • Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
    – thebjorn
    Oct 28 at 15:46










  • @thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
    – titansarus
    Oct 28 at 15:49












  • what is max n?
    – Kozyr
    Oct 29 at 6:42
















2














We get non negative integer number n from user and we must print all subsets of set ({1,2,3,...,n}). (n<=20)



for example for n=3 we must print:



{1 , 2 , 3}
{1 , 2}
{1 , 3}
{1}
{2 , 3}
{2}
{3}
{}


,s are optional and the sequence can be printed without any comma. (like {1 2 3})
I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. (lexicographical from the largest subset (the set itself) to null set)



I see a lot of codes in the Internet that solve this problem with arrays or using a bit array that indicate whether we use a number or not. The issue is that in this question, we are not allowed to use -any- type of array or other data structures like vector ,etc. Even using the array behaviour of something like string is completely prohibited. It must be solved only with recursion.



We are also not allowed to use any advanced functions. For example if we write it with C, we are allowed just to use stdio.h or for C++, only <iostream> is allowed and no other library.



I don't know how to do this without any arrays. How to check which number it must print and at the sametime, manage the {}.



PS1.
The question is simply generation powerset with these conditions:



USING ARRAY, STRING AND EVEN LOOPS ARE COMPLETELY PROHIBITED. JUST RECURSION.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.



PS2.



I write this code by help of George but it doesn't works fine. It doesn't have something like 1 2 4. It also repeats some cases.



#include <stdio.h>


void printAllSets (int size)
{printRows (size, 1);}

void printRows (int size , int start)
{
if (start<=size)
{printf( "{ ");
printRow (start, size);
printf ("}");
printf ("n");}
if (start <= size)
{printRows(size -1 , start);
printRows (size , (start + 1));}
}
printRow (int start, int limit)
{

if (start <= limit)
{

printf ("%d ",start);
printRow (start +1, limit);
}
}


int main()
{
printAllSets(5);
printf("{ }");
return 0;
}


PS3.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.










share|improve this question
























  • Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
    – thebjorn
    Oct 28 at 15:46










  • @thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
    – titansarus
    Oct 28 at 15:49












  • what is max n?
    – Kozyr
    Oct 29 at 6:42














2












2








2


3





We get non negative integer number n from user and we must print all subsets of set ({1,2,3,...,n}). (n<=20)



for example for n=3 we must print:



{1 , 2 , 3}
{1 , 2}
{1 , 3}
{1}
{2 , 3}
{2}
{3}
{}


,s are optional and the sequence can be printed without any comma. (like {1 2 3})
I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. (lexicographical from the largest subset (the set itself) to null set)



I see a lot of codes in the Internet that solve this problem with arrays or using a bit array that indicate whether we use a number or not. The issue is that in this question, we are not allowed to use -any- type of array or other data structures like vector ,etc. Even using the array behaviour of something like string is completely prohibited. It must be solved only with recursion.



We are also not allowed to use any advanced functions. For example if we write it with C, we are allowed just to use stdio.h or for C++, only <iostream> is allowed and no other library.



I don't know how to do this without any arrays. How to check which number it must print and at the sametime, manage the {}.



PS1.
The question is simply generation powerset with these conditions:



USING ARRAY, STRING AND EVEN LOOPS ARE COMPLETELY PROHIBITED. JUST RECURSION.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.



PS2.



I write this code by help of George but it doesn't works fine. It doesn't have something like 1 2 4. It also repeats some cases.



#include <stdio.h>


void printAllSets (int size)
{printRows (size, 1);}

void printRows (int size , int start)
{
if (start<=size)
{printf( "{ ");
printRow (start, size);
printf ("}");
printf ("n");}
if (start <= size)
{printRows(size -1 , start);
printRows (size , (start + 1));}
}
printRow (int start, int limit)
{

if (start <= limit)
{

printf ("%d ",start);
printRow (start +1, limit);
}
}


int main()
{
printAllSets(5);
printf("{ }");
return 0;
}


PS3.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.










share|improve this question















We get non negative integer number n from user and we must print all subsets of set ({1,2,3,...,n}). (n<=20)



for example for n=3 we must print:



{1 , 2 , 3}
{1 , 2}
{1 , 3}
{1}
{2 , 3}
{2}
{3}
{}


,s are optional and the sequence can be printed without any comma. (like {1 2 3})
I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. (lexicographical from the largest subset (the set itself) to null set)



I see a lot of codes in the Internet that solve this problem with arrays or using a bit array that indicate whether we use a number or not. The issue is that in this question, we are not allowed to use -any- type of array or other data structures like vector ,etc. Even using the array behaviour of something like string is completely prohibited. It must be solved only with recursion.



We are also not allowed to use any advanced functions. For example if we write it with C, we are allowed just to use stdio.h or for C++, only <iostream> is allowed and no other library.



I don't know how to do this without any arrays. How to check which number it must print and at the sametime, manage the {}.



PS1.
The question is simply generation powerset with these conditions:



USING ARRAY, STRING AND EVEN LOOPS ARE COMPLETELY PROHIBITED. JUST RECURSION.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.



PS2.



I write this code by help of George but it doesn't works fine. It doesn't have something like 1 2 4. It also repeats some cases.



#include <stdio.h>


void printAllSets (int size)
{printRows (size, 1);}

void printRows (int size , int start)
{
if (start<=size)
{printf( "{ ");
printRow (start, size);
printf ("}");
printf ("n");}
if (start <= size)
{printRows(size -1 , start);
printRows (size , (start + 1));}
}
printRow (int start, int limit)
{

if (start <= limit)
{

printf ("%d ",start);
printRow (start +1, limit);
}
}


int main()
{
printAllSets(5);
printf("{ }");
return 0;
}


PS3.



User Kosyr submitted a very good answer with bit operators. So if you want to submit another answer, submit an answer that even doesn't use bit operators.







algorithm recursion subset powerset






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Oct 29 at 9:10

























asked Oct 28 at 15:41









titansarus

1076




1076












  • Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
    – thebjorn
    Oct 28 at 15:46










  • @thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
    – titansarus
    Oct 28 at 15:49












  • what is max n?
    – Kozyr
    Oct 29 at 6:42


















  • Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
    – thebjorn
    Oct 28 at 15:46










  • @thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
    – titansarus
    Oct 28 at 15:49












  • what is max n?
    – Kozyr
    Oct 29 at 6:42
















Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
– thebjorn
Oct 28 at 15:46




Hint: print all the subsets of length zero, then print all the subsets of length 1, etc. until finally print the only subset of length n.
– thebjorn
Oct 28 at 15:46












@thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
– titansarus
Oct 28 at 15:49






@thebjorn I don't know how to do this. I must add that the sequence of subsets must be exactly like the example. Meaning first the subsets that have 1, then subsets that have 2 and .... The longest subset must be printed first. not just length zero. then length 1 and ...
– titansarus
Oct 28 at 15:49














what is max n?
– Kozyr
Oct 29 at 6:42




what is max n?
– Kozyr
Oct 29 at 6:42












4 Answers
4






active

oldest

votes


















1














Recursive algorithms are very memory intensive. Here algorithm for n <= 31



#include <iostream>

void bin(unsigned bit, unsigned k, unsigned max_bits) {
if (bit == max_bits) {
std::cout << "{";
bin(bit - 1, k, max_bits);
}
else {
if ((k & (1u << bit)) != 0) {
std::cout << (max_bits - bit) << " ";
}
if (bit != 0) {
bin(bit - 1, k, max_bits);
}
else {
std::cout << "}" << std::endl;
}
}
}

void print(unsigned k, unsigned n, unsigned max_bits) {
bin(max_bits, k, max_bits);
if (k != 0) {
print(k - 1, n, max_bits);
}
}

int main()
{
unsigned n;
std::cin >> n;
print((1u << n) - 1u, 1u<<n, n);
return 0;
}


First recursion print enumerates k from 2^n-1 to 0, second recursion bin enumerates all bits of k and print non-zero bits. For example, max_bits = 5 and k = 19 is 10011b = 16 + 2 + 1 = 2^4 + 2^1 + 2^0, bits 4,1,0 interoperate as set {5-4,5-1,5-0} => {1,4,5}






share|improve this answer























  • Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
    – titansarus
    Oct 29 at 8:22












  • Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
    – titansarus
    Oct 29 at 8:26












  • Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
    – Kozyr
    Oct 29 at 8:43










  • Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
    – titansarus
    Oct 29 at 8:47










  • recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
    – George
    Nov 2 at 15:36



















1














The alternative to loops is recursion.



To solve this problem (I think...haven't tested it), I investigate the problem by tabulating the sample date and discerned three states, Size, Start, and Limit with progression as follows:



Size  Start Limit   Output
10 1 10 1..10
10 1 9 1..9
... ...
10 1 1 1
10 2 10 2..10
10 2 9 2..9
... ...
10 2 2 2
... ... ...
10 10 10 10


The following recursive algorithm in pseudo code may do the trick:



printAllSets size
printRows size 1

printRows size start
print "{"
printRow start size
print "}"
print CRLF
if start <= size
printRows size (start + 1)

printRow start limit
if start <= limit
print start + SPACE
printRow start (limit - 1)


Hope this at least helps point you in the right direction.






share|improve this answer

















  • 1




    Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
    – titansarus
    Oct 28 at 19:40








  • 1




    @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
    – erip
    Oct 28 at 20:48












  • @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
    – titansarus
    Oct 28 at 20:52












  • @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
    – George
    Nov 12 at 17:51



















1














I think we can solve this iteratively, which we can assume could also be converted to recursion, although it seems unnecessary. Consider that we can unrank any of the combinations given its index, using common knowledge. So all we need to do is count how many earlier combinations we are skipping and how many we need to unrank at each stage of the iteration (I may have missed something in the following but I think the general idea is sound):



Skip 0, unrank from `3 choose 3`
`2 choose 2` combinations
{1 , 2 , 3}

Skip 0, unrank from `3 choose 2`
`2 choose 1` combinations
{1 , 2}
{1 , 3}

Skip 0, unrank from `3 choose 1`
`2 choose 0` combinations
{1}

Skip `3 choose 2 - 2 choose 2`,
unrank from `3 choose 2`
`1 choose 1` combinations
{2 , 3}

Skip `3 choose 1 - 2 choose 1`,
unrank from `3 choose 1`
`1 choose 0` combinations
{2}

Skip `3 choose 1 - 1 choose 1`,
unrank from `3 choose 1`
`0 choose 0` combinations
{3}

Empty set
{}





share|improve this answer





























    0














    By definition, the powerset of a set k, powerset k, is the set of all possible sets containing elements from that given set including the empty set itself. Clearly, when k is the empty set powerset is simply the set containing the empty set, [ ]. Now, given a power set of k, powerset k, the powerset for k plus an additional element, E, powerset (K+E), would include all possible sets containing elements without E, powerset k, plus those same elements except now all containing E



    pseudo code...



    let powerset k =
    match k with
    | -> []
    | x:xs -> x * powerset xs + powerset xs


    or with tail call equivalent performance



    let powerset k =
    let (*) e ess = map (es -> e::es) ess
    reduce (e ess -> (e * ess) ++ ess) [ ] (reverse k)


    ....(In F#)



    let rec powerset k =
    match k with
    | -> [ ]
    | x::xs ->
    let withoutE = powerset xs
    let withE = List.map (fun es -> x::es) withoutE
    List.append withE withoutE


    or more succinctly



    let rec powerset = function
    | -> [ ]
    | x::xs -> List.append (List.map (fun es -> x::es) (powerset xs)) (powerset xs)


    A better version would allow for tail call optimization...which we achieved using common functional patterns:



    let rec powerset2 k = 
    let inline (++) a b = List.concat [a;b]
    let inline (+*) a bs = List.map (fun b -> a::b) bs
    List.fold
    (fun ac a -> (a +* ac) ++ ac)
    [ ]
    (List.rev k)


    -- this all took me a while to rediscover. It was a fun little puzzle. :)






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53033249%2fcreating-all-subsets-recursively-without-using-array%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Recursive algorithms are very memory intensive. Here algorithm for n <= 31



      #include <iostream>

      void bin(unsigned bit, unsigned k, unsigned max_bits) {
      if (bit == max_bits) {
      std::cout << "{";
      bin(bit - 1, k, max_bits);
      }
      else {
      if ((k & (1u << bit)) != 0) {
      std::cout << (max_bits - bit) << " ";
      }
      if (bit != 0) {
      bin(bit - 1, k, max_bits);
      }
      else {
      std::cout << "}" << std::endl;
      }
      }
      }

      void print(unsigned k, unsigned n, unsigned max_bits) {
      bin(max_bits, k, max_bits);
      if (k != 0) {
      print(k - 1, n, max_bits);
      }
      }

      int main()
      {
      unsigned n;
      std::cin >> n;
      print((1u << n) - 1u, 1u<<n, n);
      return 0;
      }


      First recursion print enumerates k from 2^n-1 to 0, second recursion bin enumerates all bits of k and print non-zero bits. For example, max_bits = 5 and k = 19 is 10011b = 16 + 2 + 1 = 2^4 + 2^1 + 2^0, bits 4,1,0 interoperate as set {5-4,5-1,5-0} => {1,4,5}






      share|improve this answer























      • Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
        – titansarus
        Oct 29 at 8:22












      • Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
        – titansarus
        Oct 29 at 8:26












      • Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
        – Kozyr
        Oct 29 at 8:43










      • Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
        – titansarus
        Oct 29 at 8:47










      • recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
        – George
        Nov 2 at 15:36
















      1














      Recursive algorithms are very memory intensive. Here algorithm for n <= 31



      #include <iostream>

      void bin(unsigned bit, unsigned k, unsigned max_bits) {
      if (bit == max_bits) {
      std::cout << "{";
      bin(bit - 1, k, max_bits);
      }
      else {
      if ((k & (1u << bit)) != 0) {
      std::cout << (max_bits - bit) << " ";
      }
      if (bit != 0) {
      bin(bit - 1, k, max_bits);
      }
      else {
      std::cout << "}" << std::endl;
      }
      }
      }

      void print(unsigned k, unsigned n, unsigned max_bits) {
      bin(max_bits, k, max_bits);
      if (k != 0) {
      print(k - 1, n, max_bits);
      }
      }

      int main()
      {
      unsigned n;
      std::cin >> n;
      print((1u << n) - 1u, 1u<<n, n);
      return 0;
      }


      First recursion print enumerates k from 2^n-1 to 0, second recursion bin enumerates all bits of k and print non-zero bits. For example, max_bits = 5 and k = 19 is 10011b = 16 + 2 + 1 = 2^4 + 2^1 + 2^0, bits 4,1,0 interoperate as set {5-4,5-1,5-0} => {1,4,5}






      share|improve this answer























      • Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
        – titansarus
        Oct 29 at 8:22












      • Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
        – titansarus
        Oct 29 at 8:26












      • Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
        – Kozyr
        Oct 29 at 8:43










      • Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
        – titansarus
        Oct 29 at 8:47










      • recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
        – George
        Nov 2 at 15:36














      1












      1








      1






      Recursive algorithms are very memory intensive. Here algorithm for n <= 31



      #include <iostream>

      void bin(unsigned bit, unsigned k, unsigned max_bits) {
      if (bit == max_bits) {
      std::cout << "{";
      bin(bit - 1, k, max_bits);
      }
      else {
      if ((k & (1u << bit)) != 0) {
      std::cout << (max_bits - bit) << " ";
      }
      if (bit != 0) {
      bin(bit - 1, k, max_bits);
      }
      else {
      std::cout << "}" << std::endl;
      }
      }
      }

      void print(unsigned k, unsigned n, unsigned max_bits) {
      bin(max_bits, k, max_bits);
      if (k != 0) {
      print(k - 1, n, max_bits);
      }
      }

      int main()
      {
      unsigned n;
      std::cin >> n;
      print((1u << n) - 1u, 1u<<n, n);
      return 0;
      }


      First recursion print enumerates k from 2^n-1 to 0, second recursion bin enumerates all bits of k and print non-zero bits. For example, max_bits = 5 and k = 19 is 10011b = 16 + 2 + 1 = 2^4 + 2^1 + 2^0, bits 4,1,0 interoperate as set {5-4,5-1,5-0} => {1,4,5}






      share|improve this answer














      Recursive algorithms are very memory intensive. Here algorithm for n <= 31



      #include <iostream>

      void bin(unsigned bit, unsigned k, unsigned max_bits) {
      if (bit == max_bits) {
      std::cout << "{";
      bin(bit - 1, k, max_bits);
      }
      else {
      if ((k & (1u << bit)) != 0) {
      std::cout << (max_bits - bit) << " ";
      }
      if (bit != 0) {
      bin(bit - 1, k, max_bits);
      }
      else {
      std::cout << "}" << std::endl;
      }
      }
      }

      void print(unsigned k, unsigned n, unsigned max_bits) {
      bin(max_bits, k, max_bits);
      if (k != 0) {
      print(k - 1, n, max_bits);
      }
      }

      int main()
      {
      unsigned n;
      std::cin >> n;
      print((1u << n) - 1u, 1u<<n, n);
      return 0;
      }


      First recursion print enumerates k from 2^n-1 to 0, second recursion bin enumerates all bits of k and print non-zero bits. For example, max_bits = 5 and k = 19 is 10011b = 16 + 2 + 1 = 2^4 + 2^1 + 2^0, bits 4,1,0 interoperate as set {5-4,5-1,5-0} => {1,4,5}







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Oct 29 at 8:50

























      answered Oct 29 at 7:19









      Kozyr

      1866




      1866












      • Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
        – titansarus
        Oct 29 at 8:22












      • Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
        – titansarus
        Oct 29 at 8:26












      • Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
        – Kozyr
        Oct 29 at 8:43










      • Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
        – titansarus
        Oct 29 at 8:47










      • recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
        – George
        Nov 2 at 15:36


















      • Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
        – titansarus
        Oct 29 at 8:22












      • Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
        – titansarus
        Oct 29 at 8:26












      • Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
        – Kozyr
        Oct 29 at 8:43










      • Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
        – titansarus
        Oct 29 at 8:47










      • recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
        – George
        Nov 2 at 15:36
















      Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
      – titansarus
      Oct 29 at 8:22






      Thank you very much. But can you edit is somehow that it will print the largest ones first. I mean like my example, lexicographically from the biggest subset (the set itself) to null set? I am new to programming and It is the first time I need to use these bit operators. Also n<=20.
      – titansarus
      Oct 29 at 8:22














      Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
      – titansarus
      Oct 29 at 8:26






      Also another question: Is there any way to solve this without bit operators? (And Also not using loop and array). I mean something like hanoi tower problem? Also I must add that n<=20.
      – titansarus
      Oct 29 at 8:26














      Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
      – Kozyr
      Oct 29 at 8:43




      Updated the source for lexicographical ordering. I can't solve it recursively without arrays and bits, but n<=20 hints us to use bits :)
      – Kozyr
      Oct 29 at 8:43












      Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
      – titansarus
      Oct 29 at 8:47




      Thank you again! If there is no answers without bits in two days, I will accept your answer as the best answer. Thank you again.
      – titansarus
      Oct 29 at 8:47












      recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
      – George
      Nov 2 at 15:36




      recursive algorithms can become translated by a sufficiently optimizing compiler or interpreter if they are written as pure functions that recurse only at the end of an execution path using a technique call "tail call optimization".
      – George
      Nov 2 at 15:36













      1














      The alternative to loops is recursion.



      To solve this problem (I think...haven't tested it), I investigate the problem by tabulating the sample date and discerned three states, Size, Start, and Limit with progression as follows:



      Size  Start Limit   Output
      10 1 10 1..10
      10 1 9 1..9
      ... ...
      10 1 1 1
      10 2 10 2..10
      10 2 9 2..9
      ... ...
      10 2 2 2
      ... ... ...
      10 10 10 10


      The following recursive algorithm in pseudo code may do the trick:



      printAllSets size
      printRows size 1

      printRows size start
      print "{"
      printRow start size
      print "}"
      print CRLF
      if start <= size
      printRows size (start + 1)

      printRow start limit
      if start <= limit
      print start + SPACE
      printRow start (limit - 1)


      Hope this at least helps point you in the right direction.






      share|improve this answer

















      • 1




        Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
        – titansarus
        Oct 28 at 19:40








      • 1




        @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
        – erip
        Oct 28 at 20:48












      • @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
        – titansarus
        Oct 28 at 20:52












      • @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
        – George
        Nov 12 at 17:51
















      1














      The alternative to loops is recursion.



      To solve this problem (I think...haven't tested it), I investigate the problem by tabulating the sample date and discerned three states, Size, Start, and Limit with progression as follows:



      Size  Start Limit   Output
      10 1 10 1..10
      10 1 9 1..9
      ... ...
      10 1 1 1
      10 2 10 2..10
      10 2 9 2..9
      ... ...
      10 2 2 2
      ... ... ...
      10 10 10 10


      The following recursive algorithm in pseudo code may do the trick:



      printAllSets size
      printRows size 1

      printRows size start
      print "{"
      printRow start size
      print "}"
      print CRLF
      if start <= size
      printRows size (start + 1)

      printRow start limit
      if start <= limit
      print start + SPACE
      printRow start (limit - 1)


      Hope this at least helps point you in the right direction.






      share|improve this answer

















      • 1




        Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
        – titansarus
        Oct 28 at 19:40








      • 1




        @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
        – erip
        Oct 28 at 20:48












      • @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
        – titansarus
        Oct 28 at 20:52












      • @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
        – George
        Nov 12 at 17:51














      1












      1








      1






      The alternative to loops is recursion.



      To solve this problem (I think...haven't tested it), I investigate the problem by tabulating the sample date and discerned three states, Size, Start, and Limit with progression as follows:



      Size  Start Limit   Output
      10 1 10 1..10
      10 1 9 1..9
      ... ...
      10 1 1 1
      10 2 10 2..10
      10 2 9 2..9
      ... ...
      10 2 2 2
      ... ... ...
      10 10 10 10


      The following recursive algorithm in pseudo code may do the trick:



      printAllSets size
      printRows size 1

      printRows size start
      print "{"
      printRow start size
      print "}"
      print CRLF
      if start <= size
      printRows size (start + 1)

      printRow start limit
      if start <= limit
      print start + SPACE
      printRow start (limit - 1)


      Hope this at least helps point you in the right direction.






      share|improve this answer












      The alternative to loops is recursion.



      To solve this problem (I think...haven't tested it), I investigate the problem by tabulating the sample date and discerned three states, Size, Start, and Limit with progression as follows:



      Size  Start Limit   Output
      10 1 10 1..10
      10 1 9 1..9
      ... ...
      10 1 1 1
      10 2 10 2..10
      10 2 9 2..9
      ... ...
      10 2 2 2
      ... ... ...
      10 10 10 10


      The following recursive algorithm in pseudo code may do the trick:



      printAllSets size
      printRows size 1

      printRows size start
      print "{"
      printRow start size
      print "}"
      print CRLF
      if start <= size
      printRows size (start + 1)

      printRow start limit
      if start <= limit
      print start + SPACE
      printRow start (limit - 1)


      Hope this at least helps point you in the right direction.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Oct 28 at 18:54









      George

      7281325




      7281325








      • 1




        Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
        – titansarus
        Oct 28 at 19:40








      • 1




        @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
        – erip
        Oct 28 at 20:48












      • @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
        – titansarus
        Oct 28 at 20:52












      • @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
        – George
        Nov 12 at 17:51














      • 1




        Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
        – titansarus
        Oct 28 at 19:40








      • 1




        @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
        – erip
        Oct 28 at 20:48












      • @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
        – titansarus
        Oct 28 at 20:52












      • @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
        – George
        Nov 12 at 17:51








      1




      1




      Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
      – titansarus
      Oct 28 at 19:40






      Thank You. your pseudo code had some problems that I edited in my program. but your answer doesn't cover something like 1 2 3 4 5 7 8 9 10. (it doesn't have 6 but has all other numbers). Thank you very much anyway.
      – titansarus
      Oct 28 at 19:40






      1




      1




      @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
      – erip
      Oct 28 at 20:48






      @titansarus Your question specifically says that it's a set of integers in the range [1,n]. By that formulation, your 1 2 3 4 5 7 8 9 10 dillemma is moot.
      – erip
      Oct 28 at 20:48














      @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
      – titansarus
      Oct 28 at 20:52






      @erip I Said that for n = 10. For example {1 , 2 , 3 ,4 , 5 ,7 , 8 , 9 ,10} is a subset of {1 , 2, ... , 10} but the above algorithm don't generate that. My question is generation of Power Set without loop,array and string... using just pure recursion. I checked a lot of algorithms in the internet but even the most simple of them used at least loop or string. I found nothing that satisfies all of my problem conditions at once.
      – titansarus
      Oct 28 at 20:52














      @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
      – George
      Nov 12 at 17:51




      @titansarus I have added another answer after some thought. It is rather elegant though not tail call optimized (something you can probably contribute). It defines powerset (k+1) in terms of powerset k.
      – George
      Nov 12 at 17:51











      1














      I think we can solve this iteratively, which we can assume could also be converted to recursion, although it seems unnecessary. Consider that we can unrank any of the combinations given its index, using common knowledge. So all we need to do is count how many earlier combinations we are skipping and how many we need to unrank at each stage of the iteration (I may have missed something in the following but I think the general idea is sound):



      Skip 0, unrank from `3 choose 3`
      `2 choose 2` combinations
      {1 , 2 , 3}

      Skip 0, unrank from `3 choose 2`
      `2 choose 1` combinations
      {1 , 2}
      {1 , 3}

      Skip 0, unrank from `3 choose 1`
      `2 choose 0` combinations
      {1}

      Skip `3 choose 2 - 2 choose 2`,
      unrank from `3 choose 2`
      `1 choose 1` combinations
      {2 , 3}

      Skip `3 choose 1 - 2 choose 1`,
      unrank from `3 choose 1`
      `1 choose 0` combinations
      {2}

      Skip `3 choose 1 - 1 choose 1`,
      unrank from `3 choose 1`
      `0 choose 0` combinations
      {3}

      Empty set
      {}





      share|improve this answer


























        1














        I think we can solve this iteratively, which we can assume could also be converted to recursion, although it seems unnecessary. Consider that we can unrank any of the combinations given its index, using common knowledge. So all we need to do is count how many earlier combinations we are skipping and how many we need to unrank at each stage of the iteration (I may have missed something in the following but I think the general idea is sound):



        Skip 0, unrank from `3 choose 3`
        `2 choose 2` combinations
        {1 , 2 , 3}

        Skip 0, unrank from `3 choose 2`
        `2 choose 1` combinations
        {1 , 2}
        {1 , 3}

        Skip 0, unrank from `3 choose 1`
        `2 choose 0` combinations
        {1}

        Skip `3 choose 2 - 2 choose 2`,
        unrank from `3 choose 2`
        `1 choose 1` combinations
        {2 , 3}

        Skip `3 choose 1 - 2 choose 1`,
        unrank from `3 choose 1`
        `1 choose 0` combinations
        {2}

        Skip `3 choose 1 - 1 choose 1`,
        unrank from `3 choose 1`
        `0 choose 0` combinations
        {3}

        Empty set
        {}





        share|improve this answer
























          1












          1








          1






          I think we can solve this iteratively, which we can assume could also be converted to recursion, although it seems unnecessary. Consider that we can unrank any of the combinations given its index, using common knowledge. So all we need to do is count how many earlier combinations we are skipping and how many we need to unrank at each stage of the iteration (I may have missed something in the following but I think the general idea is sound):



          Skip 0, unrank from `3 choose 3`
          `2 choose 2` combinations
          {1 , 2 , 3}

          Skip 0, unrank from `3 choose 2`
          `2 choose 1` combinations
          {1 , 2}
          {1 , 3}

          Skip 0, unrank from `3 choose 1`
          `2 choose 0` combinations
          {1}

          Skip `3 choose 2 - 2 choose 2`,
          unrank from `3 choose 2`
          `1 choose 1` combinations
          {2 , 3}

          Skip `3 choose 1 - 2 choose 1`,
          unrank from `3 choose 1`
          `1 choose 0` combinations
          {2}

          Skip `3 choose 1 - 1 choose 1`,
          unrank from `3 choose 1`
          `0 choose 0` combinations
          {3}

          Empty set
          {}





          share|improve this answer












          I think we can solve this iteratively, which we can assume could also be converted to recursion, although it seems unnecessary. Consider that we can unrank any of the combinations given its index, using common knowledge. So all we need to do is count how many earlier combinations we are skipping and how many we need to unrank at each stage of the iteration (I may have missed something in the following but I think the general idea is sound):



          Skip 0, unrank from `3 choose 3`
          `2 choose 2` combinations
          {1 , 2 , 3}

          Skip 0, unrank from `3 choose 2`
          `2 choose 1` combinations
          {1 , 2}
          {1 , 3}

          Skip 0, unrank from `3 choose 1`
          `2 choose 0` combinations
          {1}

          Skip `3 choose 2 - 2 choose 2`,
          unrank from `3 choose 2`
          `1 choose 1` combinations
          {2 , 3}

          Skip `3 choose 1 - 2 choose 1`,
          unrank from `3 choose 1`
          `1 choose 0` combinations
          {2}

          Skip `3 choose 1 - 1 choose 1`,
          unrank from `3 choose 1`
          `0 choose 0` combinations
          {3}

          Empty set
          {}






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 30 at 4:18









          גלעד ברקן

          12.2k21439




          12.2k21439























              0














              By definition, the powerset of a set k, powerset k, is the set of all possible sets containing elements from that given set including the empty set itself. Clearly, when k is the empty set powerset is simply the set containing the empty set, [ ]. Now, given a power set of k, powerset k, the powerset for k plus an additional element, E, powerset (K+E), would include all possible sets containing elements without E, powerset k, plus those same elements except now all containing E



              pseudo code...



              let powerset k =
              match k with
              | -> []
              | x:xs -> x * powerset xs + powerset xs


              or with tail call equivalent performance



              let powerset k =
              let (*) e ess = map (es -> e::es) ess
              reduce (e ess -> (e * ess) ++ ess) [ ] (reverse k)


              ....(In F#)



              let rec powerset k =
              match k with
              | -> [ ]
              | x::xs ->
              let withoutE = powerset xs
              let withE = List.map (fun es -> x::es) withoutE
              List.append withE withoutE


              or more succinctly



              let rec powerset = function
              | -> [ ]
              | x::xs -> List.append (List.map (fun es -> x::es) (powerset xs)) (powerset xs)


              A better version would allow for tail call optimization...which we achieved using common functional patterns:



              let rec powerset2 k = 
              let inline (++) a b = List.concat [a;b]
              let inline (+*) a bs = List.map (fun b -> a::b) bs
              List.fold
              (fun ac a -> (a +* ac) ++ ac)
              [ ]
              (List.rev k)


              -- this all took me a while to rediscover. It was a fun little puzzle. :)






              share|improve this answer




























                0














                By definition, the powerset of a set k, powerset k, is the set of all possible sets containing elements from that given set including the empty set itself. Clearly, when k is the empty set powerset is simply the set containing the empty set, [ ]. Now, given a power set of k, powerset k, the powerset for k plus an additional element, E, powerset (K+E), would include all possible sets containing elements without E, powerset k, plus those same elements except now all containing E



                pseudo code...



                let powerset k =
                match k with
                | -> []
                | x:xs -> x * powerset xs + powerset xs


                or with tail call equivalent performance



                let powerset k =
                let (*) e ess = map (es -> e::es) ess
                reduce (e ess -> (e * ess) ++ ess) [ ] (reverse k)


                ....(In F#)



                let rec powerset k =
                match k with
                | -> [ ]
                | x::xs ->
                let withoutE = powerset xs
                let withE = List.map (fun es -> x::es) withoutE
                List.append withE withoutE


                or more succinctly



                let rec powerset = function
                | -> [ ]
                | x::xs -> List.append (List.map (fun es -> x::es) (powerset xs)) (powerset xs)


                A better version would allow for tail call optimization...which we achieved using common functional patterns:



                let rec powerset2 k = 
                let inline (++) a b = List.concat [a;b]
                let inline (+*) a bs = List.map (fun b -> a::b) bs
                List.fold
                (fun ac a -> (a +* ac) ++ ac)
                [ ]
                (List.rev k)


                -- this all took me a while to rediscover. It was a fun little puzzle. :)






                share|improve this answer


























                  0












                  0








                  0






                  By definition, the powerset of a set k, powerset k, is the set of all possible sets containing elements from that given set including the empty set itself. Clearly, when k is the empty set powerset is simply the set containing the empty set, [ ]. Now, given a power set of k, powerset k, the powerset for k plus an additional element, E, powerset (K+E), would include all possible sets containing elements without E, powerset k, plus those same elements except now all containing E



                  pseudo code...



                  let powerset k =
                  match k with
                  | -> []
                  | x:xs -> x * powerset xs + powerset xs


                  or with tail call equivalent performance



                  let powerset k =
                  let (*) e ess = map (es -> e::es) ess
                  reduce (e ess -> (e * ess) ++ ess) [ ] (reverse k)


                  ....(In F#)



                  let rec powerset k =
                  match k with
                  | -> [ ]
                  | x::xs ->
                  let withoutE = powerset xs
                  let withE = List.map (fun es -> x::es) withoutE
                  List.append withE withoutE


                  or more succinctly



                  let rec powerset = function
                  | -> [ ]
                  | x::xs -> List.append (List.map (fun es -> x::es) (powerset xs)) (powerset xs)


                  A better version would allow for tail call optimization...which we achieved using common functional patterns:



                  let rec powerset2 k = 
                  let inline (++) a b = List.concat [a;b]
                  let inline (+*) a bs = List.map (fun b -> a::b) bs
                  List.fold
                  (fun ac a -> (a +* ac) ++ ac)
                  [ ]
                  (List.rev k)


                  -- this all took me a while to rediscover. It was a fun little puzzle. :)






                  share|improve this answer














                  By definition, the powerset of a set k, powerset k, is the set of all possible sets containing elements from that given set including the empty set itself. Clearly, when k is the empty set powerset is simply the set containing the empty set, [ ]. Now, given a power set of k, powerset k, the powerset for k plus an additional element, E, powerset (K+E), would include all possible sets containing elements without E, powerset k, plus those same elements except now all containing E



                  pseudo code...



                  let powerset k =
                  match k with
                  | -> []
                  | x:xs -> x * powerset xs + powerset xs


                  or with tail call equivalent performance



                  let powerset k =
                  let (*) e ess = map (es -> e::es) ess
                  reduce (e ess -> (e * ess) ++ ess) [ ] (reverse k)


                  ....(In F#)



                  let rec powerset k =
                  match k with
                  | -> [ ]
                  | x::xs ->
                  let withoutE = powerset xs
                  let withE = List.map (fun es -> x::es) withoutE
                  List.append withE withoutE


                  or more succinctly



                  let rec powerset = function
                  | -> [ ]
                  | x::xs -> List.append (List.map (fun es -> x::es) (powerset xs)) (powerset xs)


                  A better version would allow for tail call optimization...which we achieved using common functional patterns:



                  let rec powerset2 k = 
                  let inline (++) a b = List.concat [a;b]
                  let inline (+*) a bs = List.map (fun b -> a::b) bs
                  List.fold
                  (fun ac a -> (a +* ac) ++ ac)
                  [ ]
                  (List.rev k)


                  -- this all took me a while to rediscover. It was a fun little puzzle. :)







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Nov 19 at 23:12

























                  answered Nov 12 at 14:56









                  George

                  7281325




                  7281325






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53033249%2fcreating-all-subsets-recursively-without-using-array%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Xamarin.iOS Cant Deploy on Iphone

                      Glorious Revolution

                      Dulmage-Mendelsohn matrix decomposition in Python