Question

How I can find a string from a set of 100 Ascii string...please need HELP

Asked by: bobby_simon

I have a set of 100 ascii strings this could be loaded from a file
A string is input from stdin.
I need to write pseudocode  that returns to stdout  a subset of strings in (1) that contain the same distinct characters (regardless of order, and regardless of how many times any particular character repeats) as input in (2).
How I can optimize this for time.
For example, if I have strings in (1): seth, ryan, morgan, ccgn
One user types in: an and the output should be "ryan", “morgan” and "ccgn"
or another user types in: hh then the output should be “seth”

Please need help to solve this using JAVA

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2005-10-11 at 13:39:18ID21591564
Tags

java

Topic

Java Programming Language

Participating Experts
5
Points
220
Comments
36

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. STDIN STDOUT?
    According to a "teach yourself Perl" book I've got here, I can reset STDOUT to the default (ie. normal STDOUT) by doing this : open(STDOUT,">-"); However, if I do this : print "Hello1\n"; open(STDOUT,">/dev/null"); prin...
  2. linux: spawn a process with different stdin / stdout
    I would like to know how to run an executeable via C code under linux. I would like hook the newly spawned process's stdin, stdout and stderror to my project. This way I can parse whats comming out of the program (stdout and stderror) and send commands to the program (std...
  3. VB executable with DOS behavior (STDIN,  and STDOUT)
    Hi, I would like to know how to build an exe in Visual Basic which behaves like a DOS or UNIX program: reading from STDIN, writing to STDOUT, raising errors into STDERR. This exe should be started by an already existing program/framework (probabely written in C) which s...
  4. Please help me to pseudocode how to find a substring from…
    I have a set of 100 ascii strings (perhaps loaded from a file) A string is input from stdin How do I write pseudocode that returns (to stdout) a subset of strings in (1) that contain the same distinct characters (regardless of order) as input in (2). For example, ...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: mightyonePosted on 2005-10-11 at 14:07:25ID: 15064552

using a hsch map, wheer the values are stored in a list
keys should be all letters a,b,c,....

when reading file parse the input and ad it to valuelist if key hits e.g. seth would be filles to values to 's', 'e', 't', and 'h'
remember to update and not overwrite your value lists

e.g.

Hashmap map = new Hashmap();
//fill with empty Arraylists as values to avoid nullpointers
e.g.
map.put("a", new ArrayList());
map.put("b", new ArrayList());...


then ad the real values

List tmp = map.getValue("s");
tmp.add("seth");
map.put("s",tmp);


and so on

make sure not to print results double...



 

by: matthewdflemingPosted on 2005-10-11 at 14:09:29ID: 15064571

Ahh homework.. those were the days.

Brute force is a starting point..
You could load the 100 strings into an array.
You could iterate over the array
Create Map matches
For each string in array
  for each letter of input
      do an indexof the first letter if found store in matches(string,num times matched)
      if found continue letter loop
  end letter loop
end loop
  iterate over matches map.entries
      if value of entry == # input letters it matches
  end iterate

 

by: matthewdflemingPosted on 2005-10-11 at 14:12:36ID: 15064597

In my solution you could also just use the map always instead of the array.. and load the map from the file to begin with.. then loop over each entry in the map in place of iterating over the array..

My solution boils down to using the 100 strings as the key to the map and the number of times a letter in input matches that string as the value of the map.

 

by: bobby_simonPosted on 2005-10-11 at 14:32:09ID: 15064740

Hello Mightyone,
     Thanks a lot, however I still not understanding such as is it the best way to solve this problems far optimization goes?

Does Hashmap supports implementations of ArrayList? My understanding is HashSet support TreeSet and HashMap supports TreeMap. Please explain or may be you can give me more directions in details about this problem and I can write a small program and test it.

Thanks again

 

by: matthewdflemingPosted on 2005-10-11 at 14:39:47ID: 15064800

>>Does Hashmap supports implementations of ArrayList?
I don't know what you mean.. Hashmap implements Map and ArrayList implements List

You don't need an arraylist to solve.. all you need is a Map with counters in my solution.  

You will need to define what optimize for time means to you.. What is optimal time? Is it linear? Like adding more values or more input characters means linear growth in time?

 

by: mightyonePosted on 2005-10-11 at 14:48:31ID: 15064845

hashmap is optimized for the keys.

so you calling gimme the value for the a key is quick

the value is of type object, so it could be everything, also a list
for further optimizing think of normalizing your input names, e.g. 'ccgn' must only be 'cgn' as the c is double
to go even further you might think of analyzing your language and pair letters e.g. in english most of the tinme after a 't' comes an 'h' so you might think of altering alter your alphabet to enter less key/values pairs

good night

 

by: mightyonePosted on 2005-10-11 at 14:49:13ID: 15064853

List tmp = map.getValue("s");

should of courde be

List tmp = (ArrayList)map.getValue("s");

 

by: matthewdflemingPosted on 2005-10-11 at 14:56:01ID: 15064898

Here is my solution written out.. obviously it would need to be tweaked to read from the args and potentially loop over the remainder.. but you should get the idea

public class Work {

    public static void main(String[] args) {
        Map storage = new HashMap();
        char[] input1 = "tt".toCharArray();
        String[] entries = new String[] {"seth", "ryan", "morgan", "ccgn"};
        for (int i = 0; i < entries.length; i++) {
            storage.put(entries[i],new Integer(0));
        }
        Set entrySet = storage.entrySet();
        for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
            Map.Entry element = (Map.Entry) iter.next();
            String key = (String)element.getKey();
            for (int i = 0; i < input1.length; i++) {
                Integer value = (Integer)element.getValue();
                if (key.indexOf(input1[i]) != -1) {
                    int newValue = value.intValue() + 1;
                    storage.put(key,new Integer(newValue));
                }
            }
        }
        for (Iterator iter = entrySet.iterator(); iter.hasNext();) {
            Map.Entry element = (Map.Entry) iter.next();
            int value = ((Integer)element.getValue()).intValue();
            if (value == input1.length) System.out.println ("Got one:" + element.getKey());
        }
    }
}

 

by: matthewdflemingPosted on 2005-10-11 at 14:59:03ID: 15064918

So you could optimize this by cutting down on the number of iterations across the input variables if you want be eliminating duplicates.  The values are already optimized in that indexof will stop at the first character that it finds.

 

by: bobby_simonPosted on 2005-10-11 at 15:41:43ID: 15065148

Thanks again however a good performance is absolutely necessary therefore loops are not a good idea at least I think so.  How about declarative programming approach in general for ASCII character set?

 

by: bobby_simonPosted on 2005-10-11 at 16:42:32ID: 15065406

As I said I am looking for declaractive  approach. It is like Declarative (SQL), most work done by Data Engine within the DBMS.

Can we define a relational logic for this ascii character set such as some kind of mathematical relation in the db level? Like some kind of parents child relationship and assert into tables.

Then use SQL to find the correct sting I am looking for?

 

by: kawasPosted on 2005-10-11 at 17:35:47ID: 15065561

if you are using sql, you would make statements like

Select * from myTable where myValue like '%an%';

where i am trying to find a substring 'an' from myTable under the column myValue

 

by: bobby_simonPosted on 2005-10-11 at 18:31:38ID: 15065685

I know sql but how I implement the whole problem using declarative approach. In other words what are the designs steps involve. Explanations of these step.

Thanks

 

by: JakobAPosted on 2005-10-11 at 19:03:18ID: 15065758

If you want it fast you should use bitsets.

Your big pool of strings are converted into a similar pool of bitsets with a bit set for each character occurring in the string

a is bit 0, b is bit 1, c is bit 2, ...    a long integer have 64 bits, that should be plenty for alphabet and digits

this way each string becomes a long, you only need to do this once. and remember which long belong to which string.

when the user type in his string you convert that to a bitset too. in the same way.

and now you can test eaxh string FAST (not sure about your exact condition, so velow are to if's for testing

    if ( ( userBitSet & poolBitSet[0] ) != 0 ) {
         // at least one of the characters in the userstring is in pool string nr 0
    }
or
    if ( ( userBitSet & poolBitSet[0] ) == userBitSet ) {
        // all of the characters in the userstring is in pool string nr 0
    }

regards JakobA

 

by: bobby_simonPosted on 2005-10-11 at 19:30:09ID: 15065824

Hi JakobA,
    I think yours approach is correct. So here is my conditions

I have a set of 100 ascii strings this could be loaded from a file
Then a string is input from stdin.

Need to write code or pseudocode that returns to stdout a subset of strings in (1) that contain the same distinct characters regardless of order, and regardless of how many times any particular character repeats as input in (2).

For example, lets say I have strings in (1): seth, ryan, morgan, ccgn
One user types in: ---> an and the output should be "ryan", “morgan” and "ccgn"
and another user types in:----> hh then the output should be “seth”

Now could you please explain yours logic one more time in details that satisfy the above mentioned logic and how I can implement it?


Thanks for yours kind help

 

by: JakobAPosted on 2005-10-11 at 19:44:53ID: 15065863

Actually, there is a problem there. Your question shout 'Homework', and by the rules of EE we must not do peoples homework for them. Abowe I gave a broad outline ( and it seems you got the idea :-)), but we cannot give you much more than that before you yourself start implementing it, then we can help you debug here and there and maybe even suggest an improvement or two.

sorry, but thems the rules.

regards JakobA

 

by: bobby_simonPosted on 2005-10-11 at 20:17:03ID: 15065929

Hi JakobA,
   I am a full time employee and I am not a student. If it was my home work assignment I would not bother to ask anyone and do whatever I can.

Therefore I hope you understand and please enlighten me what I asked before. I appreciated yours help and thank you very much.

Best Regards,

BobbyS

 

by: JakobAPosted on 2005-10-11 at 21:23:18ID: 15066124

Well ok. here is a draft. Pseudo in < > brackets, but utterly untested so you will likely find lots of syntax and spelling errors.

class BitSetString {     //objects of this class store one string along with its bitset.

    private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";
                                  //in the bitset bits are set by the characters position in the string alfabet

    private String str;
    private long bitSet;

    public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();
        int j;
        this.bitSet = 0;
        for (int i=inStr.length()-1; i >= 0; i--) {
            j = alfabet.indexOf( tempStr.charAt(i) );
            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);
        }
    }

    public boolean containNone( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == 0;
    }

    public boolean containSome( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) != 0;
    }

    public boolean containAll( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == that.bitSet;
    }

    public String toString() {
        return this.str;
    }
}// endclass BitSetString


class MainProgram {

    ArrayList pool = new ArrayList();
    <xxx>Reader fileInput;

    String readAString();
        if( <no more strings in fileInput> ) {
            return null;
        } else {
            return <string read from fileInput>;
        }
    }
   
    public static void main ( String[] args ) {
        String temp;
        BitSetString userBitSet;
        fileInput = <setup and open the file>;
        while ( null != ( temp =readAString() ) ) {
            pool.add( new BitSetString(temp) );
        }
        <close the file>;

        temp = System.in.readln()
        while ( null != ( temp = <line froms stdin> ) ) {
            userBitSet = new BitSetString(temp);
            boolean noneFoundYet = true;
            for( int i=0; i<pool.size(); i++ ){
                if( ((BitSetString)pool.get(i)).containAll(userBitSet) ){
                    if( noneFoundYet ) {
                        System.out.println( "\n\"" +temp +"\" is entirely contained in:" );
                        noneFoundYet == false;
                    }
                    System.out.println( "> " +(BitSetString)pool.get(i) );
                }
            }
            if( noneFoundYet ) {
                System.out.println( "\n\"" +temp +"\" was not contained in any of the strings" );
            }
        }
    }
}// endclass mainProgram

regards JakobA

 

by: matthewdflemingPosted on 2005-10-12 at 06:59:15ID: 15068823

>>good performance is absolutely necessary therefore loops are not a good idea

I don't really agree with this statement.. there are going to be java loops involved, unless you offload the processing somewhere else.. like a database.  Then a using "like" solution should work just fine..

The bitset approach may (it needs to be tested) faster than other approaches but most developers get confused pretty quickly by the operations on the bits and thus the solution is not very maintainable.  If this truly is not homework, then that should be taken into account.

 

by: matthiashowellPosted on 2005-10-12 at 13:13:52ID: 15072394

Considering that 100 strings even if fully sized strings are going to be entirely in memory, optimizing becomes a case of using the least I/O possible.

If you use a database, it will have to read the "table" once.  Otherwise using a brute force of loops or hashmaps or bitsets will probably not be very different in speed.

First develop a solution that works and then optimize if you need to.

 

by: bobby_simonPosted on 2005-10-13 at 01:17:47ID: 15075322

Hello JakobA,
      Thanks so much for yours monumental help. I read this programs many times and I still in the process of implementing it and then test it.

In the mean time may I ask you the following questions?

class MainProgram {

    ArrayList pool = new ArrayList();
    <xxx>Reader fileInput;

    String readAString();
        if( <no more strings in fileInput> ) {
            return null;
        } else {
            return <string read from fileInput>;
        }
    }

Where do I call this class at?  Let’s take this one at a step.  The following parts of the main program first I need to set up a FileInputStream with the input file name and BufferedReader around here (fileInput = <setup and open the file>;) right?

Then I call radAString() method which is in class MainProgram. So this method will read one string at a time from the imput 100 ASCII string …is that right?

Next pool.add gets this string whos bits just gets set up by BitSetString in this line (pool.add( new BitSetString(temp) );  ) right?

public static void main ( String[] args ) {
        String temp;
        BitSetString userBitSet;  //should it be BitSetString userBitSet = new BitSetString();    
          fileInput = <setup and open the file>;
        while ( null != ( temp =readAString() ) ) {
            pool.add( new BitSetString(temp) );
        }
        <close the file>;

If I have a class name MainProgram then should not we have a object of this class somewhere in the main? I know you mentioned this is not the complete code so I am asking you that would help me to solve problem down the road. Therefore what do you suggest?  
Since pool and readAString are into this class I need to create an instance of this class in the main and then read pool array and readAString method through instance object right? Can you give me an example please. In the same sample code you provided.

Class MainProgram  also has ArrayList pool = new ArrayList(), can I just declare a String Array here instead of ArryList? Again this is just a question and you are the master here. I mean whats the purpose of ArrayList here?

Could you please explain the following lines

if( ((BitSetString)pool.get(i)).containAll(userBitSet) ) //this is in main


Please explain this part that is the constructor of BitSetString inside the loop. It would be so helpful how this bitset works if you give some simple example.

public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();
        int j;
        this.bitSet = 0;
        for (int i=inStr.length()-1; i >= 0; i--) {
            j = alfabet.indexOf( tempStr.charAt(i) );
            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);
        }


Thank a lot and I am looking forward to hear from you.

Sincerely

BobbyS

 

by: JakobAPosted on 2005-10-13 at 02:41:52ID: 15075637

Yes.
  you save the program (text for both classes) in a file with the same name and extension .java "MainClass.java", you can rename the class to something else, but then you should change the name of the file too. that filename/classname correspondence is used by java to find the starting class.

Yes.
  (remember the 'e' in 'readAString')

Yes.
  pool end up containing all your 100 strings, each in its own BitSetString object.

No.
  you do not need to make an object of the 'starting' class. It is always static. and Oops, I forgot that in declaring its variables, they should be:
    static ArrayList pool = new ArrayList();
    static <xxx>Reader fileInput;
and the subroutine:
    static String readAString() {
consider the chicken and egg problem if you had to instantiate an object in order to get code to run, how would you get the code instantiating that object to run? :-))

Yes & No.
  If you can absolutely guarantee that there are exactly 100 strings to be read in, then you can just use an array instead of the ArrayList. I chose to yse an ArrayList because then it do not matter if you give it 10, 25, 100 or 5000 strings, an Arraylist adjust its size as needed. An array must be declared with its final size when you create it.
  If you feel you can safely use an array instead it would look like this:
    static BitSetString[] pool = new BitSetString[100];
                 //declares an array with room for 100 BitSetString objects

if( ((BitSetString)pool.get(i)).containAll(userBitSet) )
if(                                                     )   start of if statement with its condition
    ((BitSetString)pool.get(i))                             fetch BitSetString nr i from the list
                   pool.get(i)                              fetch whatever was stored in position i.
     (BitSetString)                                         cast that 'whatever' to a BitSetString object
                               .containAll(          )      in that object we call method containAll
                                           userBitSet       with the users BitSetString as parameter
the value returned by that method is a boolean and that then become the condition for the if statement.

public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();   //convert to lovercase, 'A' becomes 'a', etc
        int j;                                  //local variable used inside the loop
        this.bitSet = 0;                                          //start with a bitset of all 0's
        for (int i=inStr.length()-1; i >= 0; i--) {              // for i pointing to each letter in the string

            j = alfabet.indexOf( tempStr.charAt(i) );        //find that letter in the alfabet string
                                                                              // j point to its position (j==-1 if not found)
//                                       tempStr.charAt(i)           //fetch character nr i from string tempStr
//               alfabet.indexOf(                            )        //find position of that character in string alfabet

            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);  // set the corresponding bit in the bitset
//                                                              (1L<<j)    // 1L means the 1 value is a 'long' integer.  <<j  shift left j steps
//                                                            |               // bitwise or
//                                            this.bitSet                  // with the long variable bitSet in this object.
        }

so if the input string i "an" (as in your example) we
    find the 'n' character
    find that 'n' is the character at position 13 in the string 'alfabet' (position numbers start with nr 0)
    take a long with its lowest bit set:  0000000000000000000000000000000000000000000000000000000000000001 (64 bits)
    shift it left 13 steps                       0000000000000000000000000000000000000000000000000010000000000000
    or it into this.bitSet                       0000000000000000000000000000000000000000000000000010000000000000
    find the 'a' character
    find that 'a' is the character at position 0 in the string 'alfabet'
    take a long with its lowest bit set:  0000000000000000000000000000000000000000000000000000000000000001 (64 bits)
    shift it left 0 steps (no change)      0000000000000000000000000000000000000000000000000000000000000001
    or it into this.bitSet                       0000000000000000000000000000000000000000000000000010000000000001
each different character cause a different bit to be set, and if a character occur twice that bit is just set twice (waste of time there. but cheaper to just set the bit twice than it is to test if it has not been set already and then maybe set it)

regards JakobA

 

by: matthewdflemingPosted on 2005-10-13 at 06:55:07ID: 15077011

Here is the full version of my solution.. Once you get the solution by JakobA working please run mine right next to his.. I think you'll be suprised which one is faster.

To get this program going you will need to change the loadFromFile() method to load in your set of 100 strings.. then the program will take whatever arguments you pass and print out the matches it finds.  

import java.util.*;

public class NotHomework {

    public static void main(String[] args) {
        List storage = loadFromFile();
        for (int i = 0; i < args.length; i++) {
            findMatch(args[i],storage);
        }
    }
   
    private static void findMatch(String input,List storage) {
        char[] input1 = input.toCharArray();
        int sizeOfInput = input1.length;
        for (Iterator iter = storage.iterator(); iter.hasNext();) {
            String value = (String) iter.next();
            int count = 0;
            for (int i = 0; i < sizeOfInput; i++) {
                if (value.indexOf(input1[i]) != -1) {
                    count++;
                    if (count == sizeOfInput) System.out.println(value);
                } else {
                    break;
                }
            }
        }
    }
   
    private static List loadFromFile() {
        String[] entries = new String[] {"seth", "ryan", "morgan", "ccgn"};
        return Arrays.asList(entries);
    }
}

 

by: matthewdflemingPosted on 2005-10-13 at 07:01:32ID: 15077070

My program iterates over the list of possible values only one time per input and fails fast (the break part).  Plus you have already proven the point that bitset logic is more difficult for the novice programmer to understand.. my program is clean, short, easy to understand, and more than likely just as performant as the bitset..

 

by: bobby_simonPosted on 2005-10-13 at 13:24:09ID: 15080957

Hello JakobA,
  Thanks again and I can name the eitire following lines of code as MainProgram.java right?

MainProgram.java
___________________________________________________________________________________________
class BitSetString {     //objects of this class store one string along with its bitset.

    private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";
                                  //in the bitset bits are set by the characters position in the string alfabet

    private String str;
    private long bitSet;

    public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();
        int j;
        this.bitSet = 0;
        for (int i=inStr.length()-1; i >= 0; i--) {
            j = alfabet.indexOf( tempStr.charAt(i) );
            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);
        }
    }

    public boolean containNone( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == 0;
    }

    public boolean containSome( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) != 0;
    }

    public boolean containAll( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == that.bitSet;
    }

    public String toString() {
        return this.str;
    }
}// endclass BitSetString


class MainProgram {

    static ArrayList pool = new ArrayList();
    static <xxx>Reader fileInput;
    static String readAString() {
        if( <no more strings in fileInput> ) {
            return null;
        } else {
            return <string read from fileInput>;
        }
    }
   
    public static void main ( String[] args ) {
        String temp;
        BitSetString userBitSet;
        fileInput = <setup and open the file>;
        while ( null != ( temp =readAString() ) ) {
            pool.add( new BitSetString(temp) );
        }
        <close the file>;

        temp = System.in.readln()
        while ( null != ( temp = <line froms stdin> ) ) {
            userBitSet = new BitSetString(temp);
            boolean noneFoundYet = true;
            for( int i=0; i<pool.size(); i++ ){
                if( ((BitSetString)pool.get(i)).containAll(userBitSet) ){
                    if( noneFoundYet ) {
                        System.out.println( "\n\"" +temp +"\" is entirely contained in:" );
                        noneFoundYet == false;
                    }
                    System.out.println( "> " +(BitSetString)pool.get(i) );
                }
            }
            if( noneFoundYet ) {
                System.out.println( "\n\"" +temp +"\" was not contained in any of the strings" );
            }
        }
    }
}// endclass mainProgram
___________________________________________________________________________________________

May I request you to explain this statement

static <xxx>Reader fileInput; --> This is in the MainProgram.

What is the difference if I say like this

public class MainProgram { ......} instead class MainProgram { ..... }. I mean i know what is public means and in this case why we are not using public?

I just can't say enough thanks but yours help is remarkable.

Regards,

BobbyS

 

by: bobby_simonPosted on 2005-10-13 at 13:27:56ID: 15081001

Hello matthewdfleming,
    I implemented yours program and run through it and its working fine.


Thank you very much for yours kind help. However I may have some questions that I would like to ask in few days.

I was looking for BitSet solutions because company desire to implement something like that.


However I really appreciated yours wonderful help and I am sure you can address some of my questions.


Best Wishes and Regards,

BobbyS

 

by: JakobAPosted on 2005-10-13 at 13:49:08ID: 15081164

Yes you can put it all i an single file.

    static <xxx>Reader fileInput;
The <xxx> means I do not know which of Java's many premade readers you will use it could be
    BufferedReader, CharArrayReader, FilterReader, PipedReader, StringReader
any of them are capable of reading your file
most likely though is
    static BufferedReader = new BufferedReader( new FileReader( "filename.txt" ) );

I think you are right. the class MainProgram should be public, so
   public class MainProgram {
is more correct.

you will also need import statements for the arraylist
  import java.util.ArrayList;
and for whatever readers you decide to use. fx
  import java.io.FileReader;
  import java.io.BufferedReader;

 

by: bobby_simonPosted on 2005-11-10 at 16:52:41ID: 15270689

Hello JakobA
    So far I have implemented this


import java.util.*;
import java.io.*;

class BitSetString {    
          //objects of this class store one string along with its bitset.

    private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";
        //in the bitset bits are set by the characters position in the string alfabet

    private String str;
    private long bitSet;

    public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();
        int j;
        this.bitSet = 0;
        for (int i=inStr.length()-1; i >= 0; i--) {
            j = alfabet.indexOf( tempStr.charAt(i) );
            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);
        }
    }

    public boolean containNone( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == 0;
    }

    public boolean containSome( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) != 0;
    }

    public boolean containAll( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == that.bitSet;
    }

    public String toString() {
        return this.str;
    }
}// endclass BitSetString



public class MyBitSetString {
   
    static ArrayList pool = new ArrayList();
    static <xxx>Reader fileInput;
    static String readAString() {
        if( <no more strings in fileInput> ) {
            return null;
        } else {
            return <string read from fileInput>;
        }
    }
   
    public static void main ( String[] args ) {
        String temp;
        BitSetString userBitSet;
        FileReader fr     = new FileReader("myfile.txt" );// Read from a file
        BufferedReader br = new BufferedReader(fr);  
        //fileInput = <setup and open the file>;
        while ( null != ( temp = br.readAString() ) ) {
            pool.add( new BitSetString(temp) );
        }
        fr.close(); // <close the file>;

        //temp = System.in.readln()
        BufferedReader standbr = new BufferedReader(new InputStreamReader(System.in));
        temp = standbr.readln ();
       // while ( null != ( temp = <line froms stdin> ) ) {
        while ( null != ( temp) ) {
            userBitSet = new BitSetString(temp);
            boolean noneFoundYet = true;
            for( int i=0; i<pool.size(); i++ ){
                if( ((BitSetString)pool.get(i)).containAll(userBitSet) ){
                    if( noneFoundYet ) {
                        System.out.println( "\n\"" +temp +"\" is entirely contained in:" );
                        noneFoundYet == false;
                    }
                    System.out.println( "> " +(BitSetString)pool.get(i) );
                }
            }
            if( noneFoundYet ) {
                System.out.println( "\n\"" +temp +"\" was not contained in any of the strings" );
            }
        }
    }
}// endclass MyBitSetString

I am still not sure about this part...

static <xxx>Reader fileInput;
    static String readAString() {
        if( <no more strings in fileInput> ) {
            return null;
        } else {
            return <string read from fileInput>;
        }
    }
do you mean that make a seperate method call for external file instead of the main block the way I did it here. Such as


FileReader fr     = new FileReader("myfile.txt" );// Read from a file
BufferedReader br = new BufferedReader(fr);  
        //fileInput = <setup and open the file>;
        while ( null != ( temp = br.readAString() ) ) {
            pool.add( new BitSetString(temp) );
        }
        fr.close(); // <close the file>;



Also this part which is reading from a standard input that is what users going to type in for seaching a name etc code looks correct the way I did...

//temp = System.in.readln()
 BufferedReader standbr = new BufferedReader(new InputStreamReader(System.in));
 temp = standbr.readln ();
  // while ( null != ( temp = <line froms stdin> ) ) {
 while ( null != ( temp) ) { ..... }


Please explain me one more time the uses of this array
private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";
into class BitSetString {   }


Thank you very very much


 

by: JakobAPosted on 2005-11-11 at 23:56:11ID: 15279138

About the method  readAString()

  It is a matter of preference whether that should be written as a separate method or just included in the loop in the main program.

  My preference is to make it a separate method because hat makes the overall function of the main program easier to understand. You are free to write it inside the main methos if you like, it will work the same in either case.


Your code for reading from system.in looks fine.


private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";

  The string 'alfabet' have 2 functions.
1) It define the characters that will be considered when comparing two strings. (here only letters and digits, any commas, dashes or blanks will be ignored).
2) It defines an ordering of those characters so they will each have a unique number 'a' has nr 0, 'b' has nr 1, 'c' has nr 2, ...  The number is used to set a unique bit in the bitset for each different character.

regards JakobA

 

by: bobby_simonPosted on 2005-11-16 at 17:36:20ID: 15308346

Hello JakobA,
   Thanks again. Here is my two implementations with output result

1)
import java.util.*;
import java.io.*;

class BitSetString {    
          //objects of this class store one string along with its bitset.

    private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";
        //in the bitset bits are set by the characters position in the string alfabet

    private String str;
    private long bitSet;

    public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();
        int j;
        this.bitSet = 0;
        for (int i=inStr.length()-1; i >= 0; i--) {
            j = alfabet.indexOf( tempStr.charAt(i) );
            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);
        }
    }

    public boolean containNone( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == 0;
    }

    public boolean containSome( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) != 0;
    }

    public boolean containAll( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == that.bitSet;
    }

    public String toString() {
        return this.str;
    }
}// endclass BitSetString


public class MyBitSetString {
      
      static ArrayList pool = new ArrayList();
      
    /* static String readAString() */
     
    public static void main ( String[] args ) {
        String temp;
        BitSetString userBitSet;
        try {
          FileReader fr     = new FileReader("mynameset.txt" );
          BufferedReader br = new BufferedReader(fr);  
          while (null != (temp=br.readLine ())) {
                 temp=temp.trim();
               pool.add( new BitSetString(temp) );
          }
          fr.close(); // <close the file>;
          } catch (IOException e) {
                System.out.println("IO Error:" + e.getMessage()); }
        System.out.println( "\n\"" + "Please enter a string that you want to search or quit to quit" +"\n\"");
        //temp = System.in.readln()
        BufferedReader buf_in = new BufferedReader(new InputStreamReader(System.in));
        try {
           while ( null != ( temp = buf_in.readLine ()) ) {  
                temp = temp.trim();
                if (temp.equals("quit")) { System.exit(0);}
              
              userBitSet = new BitSetString(temp);
              boolean noneFoundYet = true;
              for( int i=0; i<pool.size(); i++ ){
                  if( ((BitSetString)pool.get(i)).containAll(userBitSet) ){
                     if( noneFoundYet ) {
                         System.out.println( "\n\"" +temp +"\" is entirely contained in:" );
                         noneFoundYet = false;
                     }
                   System.out.println( "> " +(BitSetString)pool.get(i) );
                 }
             }
             if( noneFoundYet ) {
                 System.out.println( "\n\"" +temp +"\" was not contained in any of the strings" );
             }
             System.out.println( "\n\"" + "Enter another name to search or quit to quit" +"\n");
           }
          } catch (IOException e) {
             System.out.println ("IO exception = " + e.getMessage());
      }
  }
}// endclass MyBitSetString

__________________________
mynameset.txt
josh, cory, jesse, seth, nick, hens

output

"Please enter a string that you want to search or quit to quit
"
josh

"josh" is entirely contained in:
> josh, cory, jesse, seth, nick, hens

"Enter another name to search or quit to quit

sh

"sh" is entirely contained in:
> josh, cory, jesse, seth, nick, hens

"Enter another name to search or quit to quit

ry

"ry" is entirely contained in:
> josh, cory, jesse, seth, nick, hens

"Enter another name to search or quit to quit



"" is entirely contained in:
> josh, cory, jesse, seth, nick, hens

"Enter another name to search or quit to quit

j

"j" is entirely contained in:
> josh, cory, jesse, seth, nick, hens

"Enter another name to search or quit to quit

 se

"se" is entirely contained in:
> josh, cory, jesse, seth, nick, hens

"Enter another name to search or quit to quit

quit

If you look at the output then you can see every time this program print the entire contaent of the string if its found
an exact match or a close match etc...

Q> Why...could you please tell me ?

Here is the second program

2)
import java.util.*;
import java.io.*;

class BitSetString {    
          //objects of this class store one string along with its bitset.

    private static final String alfabet = "abcdefghijklmnopqrstuvwxyz0123456789";
        //in the bitset bits are set by the characters position in the string alfabet

    private String str;
    private long bitSet;

    public BitSetString( String inStr ) {
        this.str = inStr;
        String tempStr = inStr.toLowerCase();
        int j;
        this.bitSet = 0;
        for (int i=inStr.length()-1; i >= 0; i--) {
            j = alfabet.indexOf( tempStr.charAt(i) );
            if( j >= 0 ) this.bitSet = this.bitSet | (1L<<j);
        }
    }

    public boolean containNone( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == 0;
    }

    public boolean containSome( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) != 0;
    }

    public boolean containAll( BitSetString that ) {
        return ( this.bitSet & that.bitSet ) == that.bitSet;
    }

    public String toString() {
        return this.str;
    }
}// endclass BitSetStringing


public class MyBitSetString {
      
      static ArrayList pool = new ArrayList();
      
    /* static String readAString() */
     
    public static void main ( String[] args ) {
        String temp, name;
        BitSetString userBitSet;
        try {
          FileReader fr     = new FileReader("mynameset.txt" );
          BufferedReader br = new BufferedReader(fr);  
          while (null != (temp=br.readLine ())) {
                 temp=temp.trim();
                 StringTokenizer tokens = new StringTokenizer(temp, ",");
                 while (tokens.hasMoreTokens()) {
                    name=tokens.nextToken();
                    pool.add( new BitSetString(name) );
                 }
          }
          fr.close(); // <close the file>;
          } catch (IOException e) {
                System.out.println("IO Error:" + e.getMessage()); }
        System.out.println("Please enter a string that you want to search or quit to quit\n" + "\n\"");
        BufferedReader buf_in = new BufferedReader(new InputStreamReader(System.in));
        try {
           while ( null != ( temp = buf_in.readLine ()) ) {  
                temp = temp.trim();
                if (temp.equals("quit")) { System.exit(0);}
              
              userBitSet = new BitSetString(temp);
              boolean noneFoundYet = true;
              for( int i=0; i<pool.size(); i++ ){
                  if( ((BitSetString)pool.get(i)).containAll(userBitSet) ){
                     if( noneFoundYet ) {
                         System.out.println( "\n\"" +temp +"\" is entirely contained in:" );
                         noneFoundYet = false;
                     }
                   System.out.println( "> " +(BitSetString)pool.get(i) );
                 }
             }
             if( noneFoundYet ) {
                 System.out.println( "\n\"" +temp +"\" was not contained in any of the strings" );
             }
             System.out.println( "\n\"" + "Enter another name to search or quit to quit" +"\n");
           }
          } catch (IOException e) {
             System.out.println ("IO exception = " + e.getMessage());
      }
  }
}// endclass MyBitSetString


I made changes in the code after readling a line from the external file I used StringTokenizer to break
the input line into individual name or token and then used pool.add.

StringTokenizer tokens = new StringTokenizer(temp, ",");
                 while (tokens.hasMoreTokens()) {
                    name=tokens.nextToken();
                    pool.add( new BitSetString(name) );

Here is the output
Please enter a string that you want to search or quit to quit

"
jh

"jh" is entirely contained in:
> josh

"Enter another name to search or quit to quit

sam

"sam" was not contained in any of the strings

"Enter another name to search or quit to quit

jh

"jh" is entirely contained in:
> josh

"Enter another name to search or quit to quit

nick

"nick" is entirely contained in:
>  nick

"Enter another name to search or quit to quit

cory

"cory" is entirely contained in:
>  cory

"Enter another name to search or quit to quit



"" is entirely contained in:
> josh
>  cory
>  jesse
>  seth
>  nick
>  hens

"Enter another name to search or quit to quit

quit

This program output is exactly the way I want it. If the program found an exact or close match it prints only those not the entire line.

I understand its because of  StringTokenizer.

Q> Could you please tell me if there is any other way I could code this other than StringTokenizer so that entire line or sting does
not print like first program

Q> In both the program if I just hit enter its print the entire contents of the string why ?

Q> When I compile both the program from Dos prompt I get the following message. Could you please explain why?

C:\programs\java\applet>javac MyBitSetString.java
Note: MyBitSetString.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

C:\programs\java\applet>javac -Xlint MyBitSetString.java
MyBitSetString.java:59: warning: [unchecked] unchecked call to add(E) as a member
 of the raw type java.util.ArrayList
                      pool.add( new BitSetString(name) );
                              ^
1 warning


However when I use Eclipse I don't get this warning.

Thank a lot for all yours help

 

by: JakobAPosted on 2005-11-17 at 00:39:31ID: 15309914

> If you look at the output then you can see every time this program print the entire contaent of the string if its found
> an exact match or a close match etc...
>
> Q> Why...could you please tell me ?

My mistake. from your oniginal formulation of the quiestion I assumed yeach string would be on its oven line in the inputfile. Instead you have them separated by commas, and so you are quite right to use Tokenizer to separate them.


I am not sure, but I think the warnings come from your using the newest version of java where arraylists can be declared to contain only a certain type of objects.

you could try changing:
     static ArrayList pool = new ArrayList();
to:
     static ArrayList<BitSetString> pool = new ArrayList<BitSetString>();

but I an guessing here, havent used Java.5 much.

regards JakobA



 

by: bobby_simonPosted on 2005-12-07 at 15:02:40ID: 15440708

Hi JakobA,
    I am very thankful and delighted for yours help and I managed to successfully implemted the design you have suggested.

Perhaps you can tell me something about the following:

When a customer said -> in java keyword “New” tends to fragile code.

Could you please tell me why this above remark made?

What is a good design patterns that reduce the interclass dependencies?

Could you please show me pseudo code in java how this Design patterns could be used to substitute the use of the java keyword New

Thanks a lot.
Nick

 

by: bobby_simonPosted on 2005-12-07 at 15:05:09ID: 15440722

Hi matthiashowell,
    Thank you very much for all yours help.  

Perhaps you can tell me something about the following:

When a customer said -> in java keyword “New” tends to fragile code.

Could you please tell me why this above remark made?

What is a good design patterns that reduce the interclass dependencies?

Could you please show me pseudo code in java how this Design patterns could be used to substitute the use of the java keyword New

Thanks
Nick

 

by: matthewdflemingPosted on 2005-12-08 at 07:19:55ID: 15445036

This seems like a new question?  

Here's a short answer:
When you instantiate objects using "new" you have created a coupling or hard dependency between the two classes.  This increases fragility because changing one class could affect/break the other.  The usual design pattern that solves this is the Factory pattern..  The factory sits between the two classes so there is only a dependency/coupling with the factory; if you want to change an implementation on either side the risks are more isolated.  Here's a google query that will elaborate on the pattern (http://www.google.com/search?q=java+factory+design+pattern&start=0&ie=utf-8&oe=utf-8)

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...