I got a different resolt than i was supposed to

  • Thread starter Thread starter transgalactic
  • Start date Start date
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
2 replies · 3K views
transgalactic
Messages
1,386
Reaction score
0
i tried to follow this recurstion
but instead of getting the resolt i expected i got
some thing really different

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

Code:
// 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 ]
 
Physics news on Phys.org
How is it supposed to output that?
cd
bd
bc
ad
ac
ab
Your diagram itself demonstrates why
abcd21
abcd2
abcd1
abcd
is the output ... We don't understand what its purpose is.
 
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).