If I have a 2D array that is arranged as follows :
String X[][] = new String [][] {{"127.0.0.9", "60", "75000","UDP", "Good"},
{"127.0.0.8", "75", "75000","TCP", "Bad"},
{"127.0.0.9", "75", "70000","UDP", "Good"},
{"127.0.0.1", "", "70000","UDP", "Good"},
{"127.0.0.1", "75", "75000","TCP", "Bad"}
};
I want to know the frequency of each value .. so I27.0.0.9 gets 2. How can I do a general solution for this ? In Java or any algorithm for any language ?
It looks like you need a custom data type to encapsulate each row rather than using a
String[][], but to answer your question more directly, you can use aMap<String,Integer>for each column. AHashMap<String,Integer>can be expected to do this in optimal time.Here’s a snippet to demonstrate the idea:
This produces the following output: each line is a frequency map for each column:
Note: if you don’t care about mixing values from all columns together, then you only need one
Map, instead of aList<Map>one for each column. This would make the design even worse, though. You really should encapsulate each row into a custom type, instead of a having everything mixed asString[][].For example some of those columns really looks like they should be an
enum.