user2791187
user2791187

Reputation: 5

String array - instances of unique values

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");
}

Upvotes: 0

Views: 219

Answers (5)

Prasad
Prasad

Reputation: 1188

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.

Upvotes: 1

Ron Teller
Ron Teller

Reputation: 1890

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.

Upvotes: 1

Milan Baran
Milan Baran

Reputation: 4232

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

Upvotes: 0

codeMan
codeMan

Reputation: 5758

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.

Upvotes: 0

alex
alex

Reputation: 80

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

Upvotes: 0

Related Questions