Hi,i am a new guy on this forum.I have only recently
taken to C# programming and facing a few problems.I hope
to get some help here and get to know some people.
My present problem looks like this:-
I have a 5x5 Matrix. Each cell consists a string value
ex: URL of any website.
I want to find out which string value occurs( i.e.
repeats ) maximum no. of times in the matrix.
I have a hint that BINARY SEARCH TREE will be used here
and that NODE class in c# may be used to implement
trees.
The output can be in the form of array/matrix/Binary
Search Tree etc.
I am not allowed to use unsafe block to create/access
trees.
Loading
Matthew CochranPosted May 14, 2008, 9:32 AM
A binary search tree seems like a pretty sophisticated data structure to use to solve this problem when it can be done with some simple iterations.
For example:
given the following 5X5 matrix
String[][] matrix = new String[][]
{
new String[]{"A", "B", "C", "D", "E"},
new String[]{"F", "G", "H", "I", "J"},
new String[]{"A", "B", "C", "C", "D"},
new String[]{"F", "G", "H", "H", "H"},
new String[]{"A", "B", "H", "D", "E"}
};
---------------------------------------------------------------------
You'll have to visit each "cell" whatever solution you go with, so why not use a dictionary to count all occurances like this:
Dictionary<String, Int32> counter = new Dictionary<String, Int32>();
// count the instances and put them in the dictionary
foreach (String[] strArray in matrix)
foreach(String str in strArray)
if (counter.ContainsKey(str)) // if it is there, increment the count
counter[str]++;
else
counter.Add(str, 1); // if it is not there, add it
---------------------------------------------------------------------
Then you have a couple options to get the string with the most instances. One way is through a simple iterative comparison:
KeyValuePair<String, Int32> result = new KeyValuePair<string,int>("", -1);
foreach (KeyValuePair<String, Int32> kvp in counter)
{
if (result.Value < kvp.Value)
result = kvp;
}
Console.WriteLine(result.Key + ": " + result.Value);
---------------------------------------------------------------------
Your other option would be to use LINQ syntax:
// using LINQ: It is a convienient and concise
// syntax for querying collections
KeyValuePair<String, Int32> biggest =
(from x in counter.AsQueryable()
orderby x.Value descending
select x)
.First();
Console.WriteLine(biggest.Key + ": " + biggest.Value);
---------------------------------------------------------------------
Hope this helps
-Matt