Categories:
.NET (961)
C (387)
C++ (185)
CSS (84)
DBA (8)
General (31)
HTML (48)
Java (641)
JavaScript (220)
JSP (109)
JUnit (31)
MySQL (297)
Networking (10)
Oracle (562)
Perl (48)
Perl (9)
PHP (259)
PL/SQL (140)
RSS (51)
Software QA (28)
SQL Server (5)
Struts (20)
Unix (2)
Windows (3)
XHTML (199)
XML (59)
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, 2075👍, 0💬
Popular Posts:
How does ASP.NET maintain state in between subsequent request ? Refer caching chapter.
Can you explain in brief how can we implement threading ? Private Sub Form1_Load(ByVal sender As Sys...
How To Export Data to a CSV File? - Oracle DBA FAQ - Introduction to Oracle SQL Developer If you wan...
What Happens to Your Transactions When ERROR 1213 Occurred? - MySQL FAQs - Transaction Management: C...
How To Apply Filtering Criteria at Group Level? - MySQL FAQs - SQL SELECT Query Statements with GROU...