Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generate all possible substrings

 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey everyone,

This is an assignment that I had last semester when I took my advanced programming class, but I was unable to figure it out. I stumbled across it this morning and was wondering if someone can give me some input on what's going wrong.

We were supposed to used a recursive method to generate all possible substrings of a given string without repeats.

Here's the code:




If I pass in cat into my program I get:
cat
ca
c
a
at
a
t

I'm not really sure where the repeated a is coming from.

Thanks in advance,
Hunter.
 
Uli Hofstoetter
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hunter McMillen wrote:Hey everyone,

This is an assignment that I had last semester when I took my advanced programming class, but I was unable to figure it out. I stumbled across it this morning and was wondering if someone can give me some input on what's going wrong.


If I pass in cat into my program I get:
cat
ca
c
a
at
a
t

I'm not really sure where the repeated a is coming from.

Thanks in advance,
Hunter.


I did not really look at the code, but it looks like the substrings "ca" and "at" are extracted from cat.

Then "ca" is further divided into "c" and "a" as well as "at" is further divided into "a" and "t".

 
fred rosenberger
lowercase baba
Bartender
Posts: 12183
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
not printing duplicates could get hard. imagine if your input string is "the fat cat sat on a rat". it's easy to see how you might get "at" a lot...

What I'd probably do is generate each one like you are, but instead of printing it, insert it into a set.

Then, after you are all done generating them, iterate over your set elements to print them out.
 
Hunter McMillen
Ranch Hand
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the help guys, i figured it out.


This is what I changed it to:





Hunter.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49733
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well done
 
Piet Verdriet
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:Well done


Seconded!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic