DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

+ Reply to Thread
Results 1 to 3 of 3
  1. #1
    Join Date
    Jul 2005
    Posts
    1

    having difficulty with an exercise!!

    Im new to java and im having a problem with one of the questions.
    Here is the exercise:

    Im suppose to write a problem that eccepts a 5-letter word from user
    and then it generates all possible three letter words or combinations that can be derived from the 5-letter word.

    Please get me started.

  2. #2
    Join Date
    Aug 2003
    Posts
    313
    Combination and permutation algorithms can be implemented using recursion. Maybe give something like this a shot:
    Code:
    public void permutations(String input, int length, String current, Set<String> answer) {
      if( current.length() == length ) answer.add(current);
      else {
        for(int i = 0; i < input.length; i++) {
          String rest = input.substring(0, i) + input.substring(i+1);
          permutations(rest, lengtht, current+input.charAt(i), answer);
        }
      }
    }
    After calling permutations your set will be filled with the permutations of the given string that have the given length. I hope this helps to get started.
    ~evlich

  3. #3
    Join Date
    Jul 2005
    Location
    the Netherlands
    Posts
    128
    I think this is more to your liking:

    Code:
    public class Test  {
        public static void main(String[] args) {
            String s = "abcde";
            
            for(int i = 0; i < s.length()-2; i++) {
                String subs = s.substring(i,i+3);
                System.out.println("Getting index "+i+"-"+(i+3)+" from: \""+s+"\", resulting in: \""+subs+"\"");
            }
        }
    }
    Good luck!

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


Top DevX Stories

Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL


Sponsored Links