Categories:
.NET (357)
C (330)
C++ (183)
CSS (84)
DBA (2)
General (7)
HTML (4)
Java (574)
JavaScript (106)
JSP (66)
Oracle (114)
Perl (46)
Perl (1)
PHP (1)
PL/SQL (1)
RSS (51)
Software QA (13)
SQL Server (1)
Windows (1)
XHTML (173)
Other Resources:
Calculating Most Frequent Number
Can you write a computer code for the following problem:
Given an online stream of infinite numbers, print out the most frequent number.
✍: .fyicenter.com
Here is a solution in Java:
import java.io.*;
import java.util.*;
public class MostFrequent {
public static void main(String[] a) {
int mapMax = 99; // Most frequent item that appears at least 1% of the time
int mapSize = 0;
String hiItem = null;
Hashtable<String, Long> countMap = new Hashtable<String, Long>();
try {
BufferedReader input = new BufferedReader(new FileReader(a[0]));
String line = null;
while ( (line = input.readLine()) != null ) {
String item = line.trim();
Long count = countMap.get(item);
long curCount = 1;
if ( count!=null ) {
curCount = count.longValue()+1;
countMap.put(item, curCount);
} else {
if ( mapSize==mapMax ) mapSize = freeMapSpace(countMap, mapSize, mapMax);
countMap.put(item, curCount);
mapSize++;
}
if ( hiItem!=null ) {
Long hiCount = countMap.get(hiItem);
if ( hiCount==null || hiCount.longValue()<curCount ) hiItem = new String(item);
} else {
hiItem = new String(item);
}
System.out.println("Most frequent item: "+hiItem);
}
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static int freeMapSpace(Hashtable<String, Long> countMap, int mapSize, int mapMax) {
while ( mapSize==mapMax ) {
Enumeration<String> items = countMap.keys();
while(items.hasMoreElements()) {
String item = items.nextElement();
Long count = countMap.get(item);
if ( count.longValue() <= 1 ) {
countMap.remove(item);
mapSize--;
} else {
countMap.put(item, count.longValue()-1);
}
}
}
return mapSize;
}
}
2013-12-19, 2705👍, 0💬
Popular Posts:
How do you locate the first X in a string txt? A) txt.find('X'); B) txt.locate('X'); C) txt.indexOf(...
How To Download and install PSP Evaluation? - PSP Tutorials - Fading Images to Background Colors wit...
What is the difference between RegisterClientScriptBloc kand RegisterStartupScript? RegisterClientSc...
How Many Tags Are Defined in HTML 4.01? There are 77 tags defined in HTML 4.01: a abbr acronym addre...
WHat will be the result of the following code? #define TRUE 0 // some code while (TRUE) { // some co...