satincorvo
satincorvo

Reputation: 173

how do i count duplicates in an array list?

i'm currently working on a small project/game that involves guessing words that end in a certain character. in order to win, the player must beat the computer in guessing 3 words that all end in the same letter. For instance, if i choose cookies, snickers, and libraries, i would win because all 3 end in the letter "s."

in my game, each word is processed as it is played and the last character is added to an array list. What is the most efficient method of checking and counting if this letter already exists in the array list? I saw some things on removing duplicates and such, but in my case, I need to be able to identify duplicates and make sure that 3 of the same character exist inside the array list.

Upvotes: 0

Views: 440

Answers (3)

Ken
Ken

Reputation: 1393

You can use this below code:

ArrayList<Character> characterArrayList;//Remember init arrayList and add elements...
    int[] result = new int[26];
    for (char c : characterArrayList){
        result[c - 'a'] ++;
    }

Upvotes: 0

T. Claverie
T. Claverie

Reputation: 12246

As long as it works and produces the expected result, then it's fine. Plus, the solution you describe in your comment can work. That is, create an array of 26 ints and increment it based on the letter.

It is possible to transform a character into an int by casting it. In order to numerate them from 0 to 25, you can do (int) (c - 'a') to get the index. (int) ('a' - 'a') is 0, (int) ('b' - 'a') is 1 etc...

Upvotes: 1

mawalker
mawalker

Reputation: 2070

1) copy the array list 'a' to 'b'

2) sort 'b' (this allows step #3 to be done in one linear pass)

3) iterate through 'b' and keep track of where repeat are.

4) do whatever math you want based on the results

This trades off memory usage for processing speed (plus retaining the original array list as is) (sort is N lg N + 1 N for iteration through list = 2N lg N )

Upvotes: 0

Related Questions