Sum unequal length arrays

  • Thread starter Thread starter piyush varma
  • Start date Start date
P

piyush varma

Guest
I need help to verify and improve my C# code to add individual integer single digit array elements. Since the numbers could be large not represented by C# types, it as decided to store them in integer arrays.

I have following code to do that. Can I improve it and is it working for various combinations please.

/*
Test Data and result:
int[] Aa = { 1, 9, 5, 6};
int[] Bb = { 9, 2, 4};
int[] ra = {0, 2, 8, 8, 0}

int[] Aa = {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
int[] Bb = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
int[] ra = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0};

*/
static void Main(string[] args)
{
// Sum two arrays of unequal lengths

int[] Aa = {9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9};
int[] Bb = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1};

int[] TotalArray = SumArray(Aa, Bb);

TotalArray = SumUnequalLengthArrays(Aa, Bb);

}

static int[] SumUnequalLengthArrays(int[] arr1, int[] arr2)
{
// Add two corresponfing elemts of the arrays
// Its needed to sum a really largre numbers not possible to store in default types
// Add prefix zeroes to the shorter array to make it of the same length!
// Then its easier to add w/o complications

int carryOver = 0;

// find length of larger of the two arrays
int LongerLenth = ((arr1.Length >= arr2.Length) ? arr1.Length : arr2.Length);
int offset = ((arr1.Length >= arr2.Length) ? arr1.Length - arr2.Length : arr2.Length - arr1.Length);

int[] resultArray = new int[(LongerLenth + 1)];

// Start summing two array elements backward!
for (int j = LongerLenth - 1; j >= 0; j--)
{
// start from the last element
int elemOne = GiveArrayElementOrZero(arr: arr1, arrIndex: j, maxLength: LongerLenth, offset: offset);
int elemTwo = GiveArrayElementOrZero(arr: arr2, arrIndex: j, maxLength: LongerLenth, offset: offset);

int sumOfTwoDigits = 0;

int tmpDigitSum = elemOne + elemTwo + carryOver;

if (tmpDigitSum > 9)
{
carryOver = 1;
sumOfTwoDigits = tmpDigitSum - 10;
}
else
{
sumOfTwoDigits = tmpDigitSum;
carryOver = 0;
}

// Assign the result array digit, had to adjust for the carryover digit position
resultArray[j + 1] = sumOfTwoDigits;

}

// assign final carryOver digit
resultArray[0] = carryOver;

return resultArray;
}



Any suggestion will be most welcome and improve my coding skill. Thank you, Piyush Varma


piyush varma

Continue reading...
 
Back
Top