having difficulty with an exercise!!


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: having difficulty with an exercise!!

  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!

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


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center