Reputation: 107
I have a String
array for the passenger's nationality;
String[] strNationality = new String[];
Users can input any nationality they like. However I have to find the average nationality. So, for example, if there were five people on bus of nationalities; German, German, German, French, Spanish. I can see German is clearly the average looking at it, but what would be the best way to create a method calculating the average?
Upvotes: 0
Views: 1079
Reputation: 3181
I am assuming that your intention by average means most repeated country name. You can use a HashMap datastructure.
HashMap< String, Integer >: where String is the country name and Integer is going to be the count.
Once you are done with all the input, you simply need to iterate through the HashMap to find the largest value part and print the corresponding key part.
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
In your case it would look like:
KEY -> VALUE Germany -> 3 French -> 1 Spanish -> 1
Iterating through VALUE part of the Map would help you identify that 3 is the largest one and its key Germany is the one that you should be printing.
Algorithm would look like this:
Upvotes: 0
Reputation: 701
String[] strNationality = new String[]; //this array must be filled first.
string _MajorNationality = "";
int _RepeatedTimes = 0;
for(int i = 0; i < strNationality.length; i++){
int currentRepeat = 0;
for(int j = i; j < strNationality.length; j++){
if(strNationality[i].equals(strNationality[j])){
currentRepeat++;
}
}
if(_RepeatedTimes < currentRepeat){
_MajorNationality = strNationality[i];
_RepeatedTimes = currentRepeat;
}
}
//_MajorNationality would be the most repeated nationality.
//_RepeatedTimes would be how many times it repeated.
Upvotes: 0
Reputation: 1375
If there is an unknown number of nationalities, I would use Map
to store the nationality as the key
and the count as the value
. If the next nationality exists, increment the value of that nationality within the Map
object. If not, then create and new one and add it onto the Map
object.
Map<String, Integer> nationalityCount = new Map<String, Integer>();
for(int i = 0 ; i < strNationality.length(); i++) {
String nationality = strNationality[i];
if(nationalityCount.containsKey(nationality) {
int newCount = nationalityCount.get(nationality) + 1;
nationalityCount.put(nationality, newCount);
}
else {
nationalityCount.put(nationality, 1);
}
}
Upvotes: 4