I will rate Program 2 Array In this exercise you wil write s
Solution
array_utils.h
#ifndef ARRAY_UTILS_H_
#define ARRAY_UTILS_H_
int dotProduct( const int* a, int size, const int* b, int size2 );
int numPrime( const int* a, int size );
int* arrayDifference( const int* a, const int* b, int sizeOfA, int sizeOfB );
int* arrayIntersect( const int* a, const int* b, int sizeOfA, int sizeOfB );
#endif
array_utils.c
#include \"array_utils.h\"
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int dotProduct( const int* a, int size, const int* b, int size2 ){
int res = 0;
if( size != size2 ){
printf(\"%s\ \", \"Dot product not possible: vectors are of unequal size\");
return -1;
}
int i = 0;
for(; i < size; i++ ){ res = res + a[i]*b[i]; }
return res;
}
int isPrime( int n ){
int i = 2;
for(; i*i <= n; i++ ){
if( n%i == 0 ){ return 0;}
}
return 1;
}
int numPrime( const int* a, int size ){
int i = 0;
int numOfPrime = 0;
for(; i < size; i++){
if( isPrime(a[i] == 1) ){
numOfPrime++;
}
}
return numOfPrime;
}
int* arrayDifference( const int* a, const int* b, int sizeOfA, int sizeOfB ){
int i = 0, j = 0;
int InANotInB[sizeOfA];
int newSize = sizeOfA;
for(; i < sizeOfA; i++){ InANotInB[i] = 1; }
for( i =0; i < sizeOfA; i++){
for(j =0; j < sizeOfB; j++){
if( a[i] == b[j] ){ InANotInB[i] = -1; newSize--; }}}
for( i =0; i < sizeOfA; i++){
if( InANotInB[i] == -1 ){ continue; }
for(j = i+1; j < sizeOfA; j++){
if( a[i] == a[j] ){
newSize--;
InANotInB[j] = -1; }}}
int* res = (int*)malloc(4*newSize);
j = 0;
for( i = 0; i < sizeOfA; i++){
if( InANotInB[i] != -1 ){
res[j] = a[i];
j++;
}
}
printf(\"New size is: %d\ \", newSize );
return res;
}
int* arrayIntersect( const int* a, const int* b, int sizeOfA, int sizeOfB ){
int i = 0, j = 0;
int InANotInB[sizeOfA];
int newSize = 0;
for(; i < sizeOfA; i++){ InANotInB[i] = -1; }
for( i =0; i < sizeOfA; i++){
for(j =0; j < sizeOfB; j++){
if( a[i] == b[j] ){
if( InANotInB[i] == -1 ){ newSize++; }
InANotInB[i] = 1;
}}}
for( i =0; i < sizeOfA; i++){
if( InANotInB[i] == -1 ){ continue; }
for(j = i+1; j < sizeOfA; j++){
if( a[i] == a[j] ){
newSize--;
InANotInB[j] = -1; }}}
int* res = (int*)malloc(4*newSize);
j = 0;
for( i = 0; i < sizeOfA; i++){
if( InANotInB[i] != -1 ){
res[j] = a[i];
j++;
}
}
printf(\"New size is: %d\ \", newSize );
return res;
}
driver.c
#include \"array_utils.h\"
#include <stdio.h>
int main(){
int a[] = {1,2,3,4,5};
int b[] = {2,3,4,1};
int* c = arrayDifference( a , b, 5, 4 );
printf(\"%d\ \", c[0] );
int* d = arrayIntersect( a , b, 5, 4 );
printf(\"%d %d %d %d \ \", d[0] , d[1], d[2], d[3]);
return 0;
}
One problem is that by definition of arrayIntersect and arrayDifference, it is unclear as how to return size of new array, so I coded as if we knew the final size of allocated array beforehand


