7
\$\begingroup\$

Description

need to find out the paragraph number which is containing all the words in the file.

input file java.txt

What is a JVM?

What is the most important feature of Java?

Are JVM's platform independent?

What do you mean by platform independence? What is the most important feature of Java? What is a JVM? Are JVM's platform independent?

Output

paragraph num : 4

Solution code:

 public class WordsOfParagraphWithMap {
        public void findParagraphWithAllWords() throws IOException{ 

        File file = new File("C:\\Users\\VENKAT\\Documents\\javaquestions.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        int paraNum = 1;
        int count = 0;
        String line;
        int paragraphWithMaxWords = 0;
        int maxWords = 0;

        Map<String, Integer> map = new HashMap<String, Integer>();

        line = nextLine(bufferedReader);

        do {
            if (line != null) {

                if (line.trim().isEmpty()) {
                    if (maxWords < count) {
                        paragraphWithMaxWords = paraNum;
                        maxWords = count;
                    }
                    paraNum++;
                    count = 0;
                    line = nextLine(bufferedReader);
                }

                if(line!=null){
                    String[] words = line.split("\\s");
                    for (String word : words) {
                        if (!map.containsKey(word)) {
                            count++;
                        } else {
                            int paraNumber = map.get(word);
                            if (paraNumber != paraNum) {
                                count++;
                            }
                        }
                        map.put(word, paraNum);
                    }
                }
            }
        } while ((line = bufferedReader.readLine()) != null);

        if (maxWords < count){
            paragraphWithMaxWords = paraNum;
            maxWords = count;
        }


        if (map.size() == maxWords)
            System.out.println("paragraph num : " + paragraphWithMaxWords);
        else
            System.out.println("no such paragraph");


    }

    private String nextLine(BufferedReader bufferedReader) throws IOException{
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            if (line.trim().isEmpty()) {
                continue;
            } else {
                break;
            }
        }
        return line;
    }

    public static void main(String[] args) throws IOException {
        WordsOfParagraphWithMap wordsOfParagraphWithMap = new  WordsOfParagraphWithMap ();
        wordsOfParagraphWithMap.findParagraphWithAllWords();
    }
    }
\$\endgroup\$
  • \$\begingroup\$ It woud help us if you could provide in comments on what are you doing. Another thing you have a resource leak, close bufferedreader. And what does you first while loop does? Am not getting any point or use of that. \$\endgroup\$ – Vivek Singh Feb 9 '15 at 12:52
  • \$\begingroup\$ The code doesn't handle punctuation. You consider punctuation part of a word in the code, but that's not what the English language says. \$\endgroup\$ – Pimgd Feb 9 '15 at 13:00
5
\$\begingroup\$

Your code is suffering from a lack of functions. Functions help to identify what core parts of your code does, and makes those parts reusable. It also makes the calling code more readable.

By using functions, and extracting core components, it's easy to see the actual logic. For example, a main method like:

public static void main(String[] args) throws IOException {
    List<Set<String>> paragraphs = composeParagraphs(Paths.get("java.txt"));
    int superIndex = superSetParagraph(paragraphs);
    System.out.println("SuperSet Paragraph is " + superIndex);
}

Well, that's simple enough... how is it done?

Given a list of paragraph sets, finding the paragraph which is a superset, is easy:

private static int superSetParagraph(List<Set<String>> paras) {
    // get all words from all paragraphs.
    Set<String> allwords = paras.stream().flatMap(p -> p.stream()).collect(Collectors.toSet());
    // which paragraph has all words.
    for (int i = 0; i < paras.size(); i++) {
        if (paras.get(i).size() == allwords.size()) {
            return i + 1;
        }
    }
    return 0;
}

How do you get all paragraphs?

private static final Pattern SPACE = Pattern.compile("\\s+");

public static Set<String>words(String input) {
    return Arrays.stream(SPACE.split(input))
          .filter(word -> !word.isEmpty())
          .collect(Collectors.toSet());
}

private static List<Set<String>> composeParagraphs(Path path) throws IOException {
    Set<String> para = new HashSet<>();
    List<Set<String>> contents = new ArrayList<>();
    for (String line : Files.readAllLines(path)) {
        if (line.trim().isEmpty()) {
            // indicates a new paragraph....
            if (!para.isEmpty()) {
                contents.add(para);
                para = new HashSet<>();
            }
        } else {
            para.addAll(words(line));
        }
    }
    if (!para.isEmpty()) {
        contents.add(para);
    }
    return contents;
}

Again, functional extraction makes a difference.

\$\endgroup\$
  • \$\begingroup\$ Set<String> allwords = paras.stream().flatMap(p -> p.stream()).collect(Collectors.toSet()); could you please translate this line into java ? But in my code im going through the file only one time as well as maintaing only one hashmap. So in terms of time complexity and space complexity my code seems to be betters. lets discuss about time and space complexity \$\endgroup\$ – Venkat Kondeti Feb 9 '15 at 15:17
  • 1
    \$\begingroup\$ The code provided is Java 8. \$\endgroup\$ – bearrito Feb 9 '15 at 15:19
2
\$\begingroup\$

Reduce Duplication

   while ((line = bufferedReader.readLine()) != null) {
        if (line.trim().isEmpty()) {
            continue;
        } else {
            break;
        }
    }

This should be a function String nextLine(BufferedReader input). That would reduce some duplication from your code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.