This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Generate all possible substrings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generate all possible substrings" Watch "Generate all possible substrings" New topic
Author

Generate all possible substrings

Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

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.

"If the facts don't fit the theory, get new facts" --Albert Einstein
Uli Hofstoetter
Ranch Hand

Joined: Nov 24, 2006
Posts: 57
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".


SCEA5, Certified ScrumMaster
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11352
    
  16

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.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

Thanks for the help guys, i figured it out.


This is what I changed it to:





Hunter.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39070
    
  23
Well done
Piet Verdriet
Ranch Hand

Joined: Feb 25, 2006
Posts: 266
Campbell Ritchie wrote:Well done


Seconded!
 
GeeCON Prague 2014
 
subject: Generate all possible substrings