C # counting task

I have a problem. I add numbers to ArrayList as 156, 340 (when it is TransferIn or Buy ), etc., and then I delete them, doing it as 156, 340 (when it is TransferOut , Sell ). The following solution works for this without problems. The problem is that for some old data, employees entered an amount equal to 1500 instead of 500 + 400 + 100 + 500. How can I change it so that if there is a Sell / TransferOut and a match inside the ArrayList, it should try to add several elements from this array ArrayList and find elements that are combined together.

  ArrayList alNew = new ArrayList(); ArrayList alNewPoIle = new ArrayList(); ArrayList alNewCo = new ArrayList(); string tempAkcjeCzynnosc = (string) alInstrumentCzynnoscBezNumerow[i]; string tempAkcjeInId = (string) alInstrumentNazwaBezNumerow[i]; decimal varAkcjeCena = (decimal) alInstrumentCenaBezNumerow[i]; decimal varAkcjeIlosc = (decimal) alInstrumentIloscBezNumerow[i]; int index; switch (tempAkcjeCzynnosc) { case "Sell": case "TransferOut": index = alNew.IndexOf(varAkcjeIlosc); if (index != -1) { alNew.RemoveAt(index); alNewPoIle.RemoveAt(index); alNewCo.RemoveAt(index); } else { // Number without match encountred } break; case "Buy": case "TransferIn": alNew.Add(varAkcjeIlosc); alNewPoIle.Add(varAkcjeCena); alNewCo.Add(tempAkcjeInId); break; } } 
+2
source share
2 answers

This is a variation of the backpack problem , called the subset summation problem . Check out my answer here for a few solutions. To get the actual elements to be removed if you are using a dynamic programming approach, just save the second array that tells you which last element you added to get a specific amount, then you can use this to find a solution. Send back if you cannot make it work. If you have many numbers, I suggest a randomized algorithm in any case, it is easier to implement and increase memory size and time-efficiency (usually).

+3
source

This might be more complicated than you think:

+4
source

All Articles