-4

I have three arrays:

[0, 0, 2.5, 2.5, ]
[0, 0.5, 0, 0,]
[0, 2.0, 0, 0, ]

I am looking for an algorithm to loop through them all and add them to the first array ONLY if we can achieve the same value in the index of that array (2.5 in this case), delete them if they are added and leave out all the other arrays that do not fit (e.g. [0,0,0,0.001]), I can't even begin to wrap my head around this one, the tricky part to me is identifying whether a combination of two (or more) other arrays can fill the first one.

For example if we add [0, 0.5, 0, 0,] to [0, 0, 2.5, 2.5, ] we get [0, 0.5, 2.5, 2.5, ] and the same for the last one, so the method should be able to detect that and add them both to the first one and delete it, leaving any 'impossible' arrays.

user2498443
  • 143
  • 6

1 Answers1

0
var arraysToBeAdded = new List<decimal[]>();
const int numberOfElementsPerArray = 4;

arraysToBeAdded.Add(new decimal[numberOfElementsPerArray]{ 0.0M, 0.0M, 0.0M, 0.0M});
arraysToBeAdded.Add(new decimal[numberOfElementsPerArray]{ 4.1M, 3.1M, 2.1M, 1.1M});
arraysToBeAdded.Add(new decimal[numberOfElementsPerArray]{ 1.1M, 1.1M, 1.1M, 1.1M});

for(int j = 1; j < arraysToBeAdded.Count; ++j){
    for(int i = 0; i < 4; i++){
        arraysToBeAdded[0][i] += arraysToBeAdded[j][i];
        arraysToBeAdded[j][i] = 0;
    }
}

You can change the type contained in the arrays, I picked float but it could be anything. Also you can change the amount of items contained in the arrays.

And finally, I used a List to contain the arrays, but nothing says that the arrays contained in the list must have a size of 4, that's your responsibility.

Pacane
  • 20,273
  • 18
  • 60
  • 97
  • No, you can't just pick the type of the number. It seems the numbers really are decimals, which means your code (using `float`) wouldn't give correct results in some cases. – svick Jun 21 '13 at 14:44
  • What if I just change the declaration to decimal instead of float? Would that work? I'm not really aware of the difference to be honest. edit: I've just read that, I think it sums it up, for those who are wondering as well. http://stackoverflow.com/a/618542/505810 – Pacane Jun 21 '13 at 15:03
  • Yeah, that should work (assuming you also change all the literals from `f` to `m`). And if you don't know the difference, then you should be very careful when doing this, especially when exact equality is required. – svick Jun 21 '13 at 15:07