Sum Two Arrays

``````/*
Sum two arrays.
*/

/*
Vague question:
- assuming it means to treat the array
as two different numbers, and return an array
of the cooresponding sum (so each integer
in either array must be 0 - 9
*/

list<int> sum(vector<int> &a, vector<int> &b)
{
int a_size = a.size() - 1;
int b_size = b.size() - 1;

list<int> new_sum;

bool carry = false;
while (a_size >= 0 && b_size >= 0) {
if (carry) {
int next = a[a_size] + b[b_size] + 1;

if (next >= 10) {
carry = true;
new_sum.push_front(next % 10);
}
else {
carry = false;
new_sum.push_front(next);
}
}
else {
int next = a[a_size] + b[b_size];

if (next >= 10) {
carry = true;
new_sum.push_front(next % 10);
}
else {
carry = false;
new_sum.push_front(next);
}
}
a_size--; b_size--;
}

while (a_size >= 0) {
if (carry) {
int next = a[a_size] + 1;

if (next >= 10) {
carry = true;
new_sum.push_front(next % 10);
}
else {
carry = false;
new_sum.push_front(next);
}
}
else {
int next = a[a_size];

if (next >= 10) {
carry = true;
new_sum.push_front(next % 10);
}
else {
carry = false;
new_sum.push_front(next);
}
}
a_size--;
}

while (b_size >= 0) {
if (carry) {
int next = b[b_size] + 1;

if (next >= 10) {
carry = true;
new_sum.push_front(next % 10);
}
else {
carry = false;
new_sum.push_front(next);
}
}
else {
int next = b[b_size];

if (next >= 10) {
carry = true;
new_sum.push_front(next % 10);
}
else {
carry = false;
new_sum.push_front(next);
}
}
b_size--;
}

if (carry) new_sum.push_front(1);

return new_sum;
}

/*
Lets assume that if the arrays are of different length,
then we truncate the larger array
*/

vector<int> sum2(vector<int> &a, vector<int> &b)
{
vector<int> ar;
int min_ar = min(a.size(), b.size());
ar.reserve(min_ar);

for (int i = 0; i < min_ar; i++) {
ar.push_back(a[i] + b[i]);
}
return ar;
}

/*
Lets assume that if the arrays are of different length,
then we treat that smaller array as if has concatenated
zeros to max(ar1,ar2).length;
*/

vector<int> sum3(vector<int> &a, vector<int> &b)
{
vector<int> ar;
int max_ar = max(a.size(), b.size());
ar.reserve(max_ar);

int temp_a, temp_b = 0;
for (int i = 0; i < max_ar; i++) {
i >= a.size() ? temp_a = 0 : temp_a = a[i];
i >= b.size() ? temp_b = 0 : temp_b = b[i];
ar.push_back(temp_a + temp_b);
}
return ar;
}

int main()
{
// assumption 1
list<int> my_sum = sum(vector<int>() = { 2,0,3,2,0,3,9 }, vector<int>() = { 2,3,9,4,8,3,9,4 });
for (auto i : my_sum) {
cout << i;
}
cout << endl;

list<int> my_sum2 = sum(vector<int>() = { 9,9,9,9,9,9,9,9,9 }, vector<int>() = { 9,9,9,9,9 });
for (auto i : my_sum2) {
cout << i;
}
cout << endl;

//assumption 2
vector<int> my_sum3 = sum2(vector<int>() = { 1,2,3,4 }, vector<int>() = { 1,2,3,4,5 });
print(my_sum3);

//assumption 3
vector<int> my_sum4 = sum3(vector<int>() = { 1,2,3,4 }, vector<int>() = { 1,2,3,4,5 });
print(my_sum4);
}``````

Last updated