Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

I got a different resolt than i was supposed to

  1. Feb 14, 2008 #1
    i tried to follow this recurstion
    but instead of getting the resolt i expected i got
    some thing realy different

    http://img185.imageshack.us/my.php?image=img8290nf7.jpg

    Code (Text):

    // print all subsets of 1...n
    Public static void subsets(int n, String andAlso)
    {
          if (n==0)
          {
              System.out.println(andAlso);
          }
          else
         {
              subsets(n-1,andAlso + n);
              subsets(n-1,andAlso);
          }
    }
     
    i entered (2,abcd)
    i was supposed to get


    cd
    bd
    bc
    ad
    ac
    ab

    istead i got some other answer using this diagram
    can you tell me where i got ot wrong??

    [ February 14, 2008: Message edited by: donaldth smithts ]
     
  2. jcsd
  3. Feb 14, 2008 #2
    How is it supposed to output that?
    Your diagram itself demonstrates why
    is the output ... We don't understand what its purpose is.
     
  4. Feb 15, 2008 #3
    Your program is entertainingly mind boggling XD if it helps i think this is the run through of what it actually does:

    0: subsets(2, "abcd") Pass in n = 2 andAlso = "abcd"
    1.1: subsets(1, "abcd2") 1st line of else statement n-1 = 1 andAlso + n = "abcd2"
    1.1.1: subsets(0, "abcd21") 1st line of else statement n-1 = 0 andAlso + n = "abcd21"
    1.1.1.0: output = "abcd21" If statement so output
    1.1.2: subsets(0, "abcd2") 2nd line of else statement n-1 = 0 andAlso = "abcd2"
    1.1.2.0: output = "abcd2" If statement so output
    1.2: subsets(1, "abcd") 2nd line of else statement n-1 = 1 andAlso = "abcd"
    1.2.1: subsets(0, "abcd1") 1st line of else statement n-1 = 0 andAlso + n = "abcd1"
    1.2.1.0: output = "abcd1" If statement so output
    1.2.2: subsets(0, "abcd") 2nd line of else statement n-1 = 0 andAlso = "abcd"
    1.2.2.0: output = "abcd" If statement so output

    The main problem seems to be is what you want to do is to somehow make all possible subsets of the length you pass in (in your test case 2) of the string you pass in (in your test case "abcd") but your program logic doesn't seem right to do this, if it helps think of a string as an array of characters, it is possible to refer to each character individually. I would highly recommend netbeans to help, if you type in "String." for example it will list all methods associated with strings (save you remembering chunks of the API).
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: I got a different resolt than i was supposed to
  1. C++ file i/o (Replies: 7)

  2. Am I doing it right? (Replies: 2)

Loading...