Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

How to get the difference between 2 int arrays as a percentage

Mathematically we can solve it like Given Amount / Total Amount * 100 to get the percentage difference. But what I need is to compare 2 Integer Arrays (in C# Win App) and get the percentage of the difference. Like :

1 -----> -2
2 ----->  3
3 ----->  7
4 ----->  456
5 ----->  13

These two columns are 2 Integer Arrays and I should get the difference between them.
How can I get this? A mathematical answer or an algorithm, whatever can be used to solve the problem.

Upvotes: 0

Views: 1489

Answers (4)

Rosmarine Popcorn
Rosmarine Popcorn

Reputation: 10967

Thanks to everyone who replied to the question!
I thought about a solution these days but I'm not sure about the result. I have doubts about my work because I'm debugging it but each time with another 2 Arrays which contain more than 48.000 elements. My solution so far was like :

for(int i=0;i<arr1.length;i++)
{
  if(arr1[i] == arr2[i])
  count++;
}
double percentage = (float)count / (float)arr1.length * 100;

Upvotes: 0

decyclone
decyclone

Reputation: 30840

How about using LINQ:

        Int32[] array1 = new Int32[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        Int32[] array2 = new Int32[] { 9, 8, 7, 6, 5, 4, 3, 2, 1 };

        Int32[] array3 = array1.Zip(array2, (a1, a2) => (a1 + a2) / 2).ToArray(); // Put whatever formula you want in there.

EDIT: Daniel and CD are correct. Code has been corrected. Thanks guys.

Upvotes: 0

Dean Chalk
Dean Chalk

Reputation: 20471

try this

var i1 = Enumerable.Range(0, 10).ToArray();
var i2 = Enumerable.Range(20, 10).ToArray();
var result = i1.Select((n, i) => n * 100 / i2[i]);

Upvotes: 1

Itay Karo
Itay Karo

Reputation: 18296

What do you mean by difference? you can get the array of differences by:

int[] array = new int[arr1.Length];
for (i = 0; i < array.Length; i++)
{
  array[i] = array1[i] - array2[i];
}

Upvotes: 0

Related Questions