How to compute the number of occurance of each element in an array list?

J

John

I am designing an computer aided test system in Java.
For multiple choice question, I have a field of userResponses of ArrayList.

How do I calculate how many occurence of each type of user response?

I ask because each time a user finishes a multiple choice question, his
response is logged into the userResponses ArrayList.

Or in another word, how do I know the number of occurence of each element in
the ArrayList?

For example, this is a multiple choice question:
1. The memory strategy derived from Miller (1956) involving organizing
disparate pieces of information into one related, meaningful group is
referred to as

(a) organization

(b) the Cornell method

(c) elaborative rehearsal

(d) chunking

(e) SQ3R



one user might give his response as (a,b), another one (a,c), another one
(b,c),.....



Say finally the userResponses is composed of {(a,b), (b,c), (a,b), (b,c),
(c,d,e), (a,d,e), (c,d,e), (c,d,e)} after 8 users took this question.



How can I have the result as:



(a,b): 2

(b,c), 2

(c,d,e):3

(a,d,e):1
 
S

Stefan Ram

John said:
How can I have the result as:
(a,b): 2
(b,c), 2
(c,d,e):3
(a,d,e):1

What are the rules for when to use a colon after the closing
parenthesis, as in »(a,b): 2«, and when to use a comma, as in
»(b,c), 2«?

What are the rules for when to use a space after the character
after the closing parenthesis, as in »(a,b): 2«, and when to
use no space there, as in »(c,d,e):3«?
 
P

Patricia Shanahan

John wrote:
....
Or in another word, how do I know the number of occurence of each element in
the ArrayList?
....

Replace the ArrayList with a Map, with responses as keys, and the count
of the number of appearances so far of the response as value.

Patricia
 
S

Stefan Ram

John said:
How can I have the result as:
(a,b): 2
(b,c), 2
(c,d,e):3
(a,d,e):1

And, adding to my previous two questions:

Which rule determines the sorting order for tuples
of the same length?

~~

The following program is using my GPLd library »ram.jar«
for the tuple type:

class NumericMapUtils
{ public static <D> void addTo
( final java.util.Map<D,java.lang.Integer> map, final D d, final int i )
{ map.put( d, i +( map.containsKey( d )? map.get( d ): 0 )); }}

public class Main
{ static de.dclj.ram.type.tuple.ComparableTuple
<de.dclj.ram.type.tuple.DefaultComparableTuple>
tuple( java.lang.Comparable ... args ) { return new
de.dclj.ram.type.tuple.DefaultComparableTuple( args ); }

public static void main( final java.lang.String[] args )
{ final java.util.Map
<de.dclj.ram.type.tuple.ComparableTuple,java.lang.Integer> map =
new java.util.TreeMap
<de.dclj.ram.type.tuple.ComparableTuple,java.lang.Integer>();
NumericMapUtils.addTo( map, tuple( 'a', 'b' ), 1 );
NumericMapUtils.addTo( map, tuple( 'b', 'c' ), 1 );
NumericMapUtils.addTo( map, tuple( 'a', 'b' ), 1 );
NumericMapUtils.addTo( map, tuple( 'b', 'c' ), 1 );
NumericMapUtils.addTo( map, tuple( 'c', 'd', 'e' ), 1 );
NumericMapUtils.addTo( map, tuple( 'a', 'd', 'e' ), 1 );
NumericMapUtils.addTo( map, tuple( 'c', 'd', 'e' ), 1 );
NumericMapUtils.addTo( map, tuple( 'c', 'd', 'e' ), 1 );

for( final de.dclj.ram.type.tuple.ComparableTuple d : map.keySet() )
java.lang.System.out.println( d.toString() + map.get( d )); }}

The output is

( a; b )2
( a; d; e )1
( b; c )2
( c; d; e )3

~~

Here is a program in Java SE not using my library, and
a somewhat more specialized »NumericMap« class.
It also uses another sorting method for the output.

class NumericMap
{ final java.util.Map
<java.lang.String,java.lang.Integer> map =
new java.util.TreeMap
<java.lang.String,java.lang.Integer>();

public void increment
( final char ... a )
{ final java.lang.String s = a.length + java.util.Arrays.toString(a);
map.put( s, 1 +( map.containsKey( s )? map.get( s ): 0 )); }

public void print()
{ for( final java.lang.String d : map.keySet() )
java.lang.System.out.println( d.toString() + map.get( d )); }}

public class Main
{
public static void main( final java.lang.String[] args )
{ NumericMap numericMap = new NumericMap();
numericMap.increment( 'a', 'b' );
numericMap.increment( 'b', 'c' );
numericMap.increment( 'a', 'b' );
numericMap.increment( 'b', 'c' );
numericMap.increment( 'c', 'd', 'e' );
numericMap.increment( 'a', 'd', 'e' );
numericMap.increment( 'c', 'd', 'e' );
numericMap.increment( 'c', 'd', 'e' );
numericMap.print(); }}

The output is:

2[a, b]2
2[b, c]2
3[a, d, e]1
3[c, d, e]3
 
R

Ruan

I don't care the format.
I just want to know the number of occurence of each elements.
 
R

Ruan

Are you suggesting hashtable? What is its method to add the value of a
specifica key when a new user takes the question?

And what is the method when there is no previous key and have to add a new
one?
 
M

michaelp

Den 03.05.2007 13:59, Ruan skrev:


Are you suggesting hashtable?

This is a good suggestion. A HashTable is a map, the same is a HashMap
and other classes.
What is its method to add the value of a
specifica key when a new user takes the question?

> And what is the method when there is no previous key and have to add a new
> one?


You need to represent a response by a pattern, for example as a String
pattern, "(a,b)", "(a,c)", and so on. But you do not need to do it in
advance, as long as you have a method that generates the pattern
automatically as the response comes from the user. These patterns are
your keys.

The number of occurrence is the value, and unless you use Auto-Boxing
(dont if you do not know what it means), has to be treated as an object.
Integer is a good choice.

Now: A Map has the methods.
put(key, value) with which you associate a key with a value
and get(key), with which you extract a value based on a key.

if a key (that is automatically generated by the application) has not
been used yet, get() returns null, and you assign it with
put(Stringpattern, new Integer(1))
otherwise you increment the already existing value.

Like the following:



Integer value = (Integer)mymap.get(stringpattern);
if (value == null){
mymap.put(stringpattern, new Integer(1));
}else{
int nr_occ=value.intValue() + 1;
mymap.put(Integer.valueOf(int_nr_occ));
}

Hope it helps.

Michael
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Ruan schreef:
Are you suggesting hashtable? What is its method to add the value of a
specifica key when a new user takes the question?

No, she suggested HashMap. Have a look at the javadoc.
And what is the method when there is no previous key and have to add a new
one?

GIYF, have a look at the Javadoc.

You might also have a look at CollectionUtils in the Jakarta Commons
Collections. It contains methods like getCardinalityMap(Collection) etc.

I can provide you with a generified version if you wish.

H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGOe1Fe+7xMGD3itQRAqtOAJ9PR8wi9mDhIbBrbWqzN3q2iuke0wCcDtM/
8wKrIpCk/xvrMZnlwQLro28=
=fbzj
-----END PGP SIGNATURE-----
 
P

Patricia Shanahan

michaelp said:
Den 03.05.2007 13:59, Ruan skrev:




This is a good suggestion. A HashTable is a map, the same is a HashMap
and other classes.

I generally use HashMap in preference to Hashtable. HashMap was designed
to fit into the current collections framework.

However, depending on the best order for the results, LinkedHashMap or
TreeMap may be better. The OP should read the documentation for the Map
implementations before picking one.

Patricia
 
J

John

why do I have the following errors?

n in thread "main" java.lang.NullPointerException
at multipleChoiceQuestion.setUserResponses(multipleChoiceQuestion.java:199)
at survey.takeSurveyOrQuiz(survey.java:120)
at surveyQuizBank.takeSurveyOrQuiz(surveyQuizBank.java:83)
at connection.finishQuestion(connection.java:262)
at terminal.processKeyboardInput(terminal.java:39)
at surveyQuizTester.main(surveyQuizTester.java:19)

I guess I didnot intialize the Map properly.

userResponses=new HashMap();


Is this correct?
 
M

Michael Preminger

John said:
why do I have the following errors?

n in thread "main" java.lang.NullPointerException
at multipleChoiceQuestion.setUserResponses(multipleChoiceQuestion.java:199)
at survey.takeSurveyOrQuiz(survey.java:120)
at surveyQuizBank.takeSurveyOrQuiz(surveyQuizBank.java:83)
at connection.finishQuestion(connection.java:262)
at terminal.processKeyboardInput(terminal.java:39)
at surveyQuizTester.main(surveyQuizTester.java:19)

I guess I didnot intialize the Map properly.

userResponses=new HashMap();
The initialization is O.K, so your problem probably lies somewhere else,
beyond the scope of this question.

You will have to provide us with some more information to get a useful
answer.

Michael
 
P

Patricia Shanahan

Michael said:
The initialization is O.K, so your problem probably lies somewhere else,
beyond the scope of this question. ....
....

There is an obvious possibility in the last paragraph, failure to test
for, and handle, null result from get().

Patricia
 
H

Hendrik Maryns

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

John schreef:
Yes, please provide me with a generified version.

Please do not top-post.

It is not that easy, since a lot of other classes are involved too.

But here you go. Of course, you probably don’t need any of the other
classes, they are just included such that the class will compile. You
are free to pick out the methods you want and remove the others, but
IANAL, so have a look at the Apache license first.

H.
- --
Hendrik Maryns
http://tcl.sfs.uni-tuebingen.de/~hendrik/
==================
http://aouw.org
Ask smart questions, get good answers:
http://www.catb.org/~esr/faqs/smart-questions.html
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.5 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGOwTJe+7xMGD3itQRAoCdAJ4xTDUgd2l7XcLh+loW8/kboktaiQCfb0hc
Y1mKIYM7x3vj52QeS3qpxhU=
=AdQ6
-----END PGP SIGNATURE-----
 
J

John

Strange enough

When I change Integer value = (Integer)mymap.get(stringpattern);
TO:if (mymap.containsKey(stringpattern))

It works without error prompt.


Does anybody know why?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top