0

I wrote a program that loops through a string array and prints the unique words and their occurrences, and then prints them to a file. This part works perfectly, but I'm having trouble figuring out how to get the total count of unique words. I have a feeling I need to create an int array for a counter, but I'm not exactly grasping how to do this. Unfortunately I am NOT allowed to use Hashmap, Sets, or Lists; have to stick with Arrays.

boolean [] done = new boolean[textfile.length];
for(int i = 0; i<textfile.length; i++){
    if(done[i])
        continue;
    int nb = 0;
    for(int j = i; j < textfile.length; j++){
        if(done[j])
            continue;
        if(textfile[i].equals(textfile[j])){
            done[j] = true;
            nb++;

        }
    }

    pw.println(textfile[i] + "occurs " + nb + " times");
}
3
  • are you allowed to use set? Commented Oct 9, 2013 at 10:26
  • what is the variable nb?? Commented Oct 9, 2013 at 10:27
  • counts the instances of each unique word Commented Oct 9, 2013 at 10:28

5 Answers 5

1

I will suggest you to do as follows-

-Add all the values in an array and sort this array.(so that it will be easy to get unique entry)

-Compare all the elements of sorted array (one by one) with the word to be compared.

-Now while comparing a word in a text file with a word present in an array, maintain a global variable i.e. counter which will be incremented on every occurrence of a unique character and will persist the value for future use.

Sign up to request clarification or add additional context in comments.

Comments

1

Right now you are comparing each word with all the words after it in the file, which takes O(N^2) times, you can instead create an array containing all the words, sort it by lexicographic order which takes O(NlogN) time, then iterate through the array and count the occurrences of each unique word (if 2 adjacent words are equal, keep counting, otherwise print and reset the counter) which takes O(N) times.

1 Comment

Thanks, this is just the info I needed. I'll see if I can get this to work.
0

You could set uniqe_counter outside of first for and increment that every time when nb == 1 before printing

Comments

0

You are reinitializing the variable nb in every iteration of the outer loop. thus u end up loosing the count of unique words processed in the last iteration.

U have to place the int nb = 0; out side the first for loop.

Comments

0

The easiest way is:

  1. Sort the array
  2. Go trough the sorted array and remember last unique entry
  3. If lastUniqueEntry is different as next entry. UniqueCount + 1
  4. Do everything else, like prints the unique words and their occurrences

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.