1

I have two arrays whose elements are one to one mapped.

string [] denom = new string[]  { EUR, GBP, EUR, USD, USD};

int [] count = new int[]  { 1,  3, 4, 7, 8};

EUR - 1
GBP - 3
EUR - 4
USD - 7
USD - 8

I want to get an output into an array by summing the count based on the denom

So, EUR - 5 (1 +4), GBP - 3, USD - 15 (7+8)

The output array should have values like {5, 3 , 15}

We have a logic to remap the final count with Denoms (i.e, EUR, GBP, USD)

We want the logic in C#.net

1
  • Can you tag the language that you are using? Looks of it says Java? Commented Aug 19, 2018 at 13:04

2 Answers 2

2

To achieve desired output below code sample will help you.

string[] denom = new string[] { "EUR", "GBP", "EUR", "USD", "USD" };
int[] count = new int[] { 1, 3, 4, 7, 8 };

//Create dictionary object to manage group by denom
Dictionary<string, int> dct = new Dictionary<string, int>();

//Iterate and sum group by denom
for (int i = 0; i < denom.Length; i++)
{
    if (!dct.Keys.Contains(denom[i]))
        dct[denom[i]] = 0;
    dct[denom[i]] += count[i];
}

//Print output
foreach (KeyValuePair<string, int> kpVal in dct)
    Console.WriteLine(kpVal.Key + "=" + kpVal.Value);
dct.Clear();

See the output printed below.

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

You could simply create a map and keep up the sum as below:

Map<String, Integer> currencyValueMap = new HashMap<>();
for (int i=0; i<denom.length; i++) {
    currencyValueMap.put(denom[i], (k, v) v == null ? count[i] : count[i] + v);
}

At the end, you would be left with currency name as key while total value as a value against that particular key.

2 Comments

Thanks for the logic, but I want the logic in C#.Net. I dont see HashMap in C#.Net
Then you should add that as a tag in question

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.