I'm comparing arrays here by elements value then storing the score in score[] array
I would like to know how to print all the score array using score = compareTriplets(a,b) if possible.
If not, what is the best approach to get the output?
#include<stdio.h>
int a[3];
int b[3];
int score[] = {0,0};
int *compareTriplets(int a[], int b[]);
int *compareTriplets(int a[], int b[])
{
int i;
for(i=0;i<3;i++)
{
if( a[i] > b[i])
{
score[0] += 1;
}
else if( b[i] > a[i])
{
score[1] += 1;
}
}
return score;
}
int main()
{
int k;
int score;
scanf("%d %d %d", &a[0], &a[1], &a[2]);
scanf("%d %d %d", &b[0], &b[1], &b[2]);
score = compareTriplets(a,b);
for(k=0;k<2;k++)
{
printf("%d",score[k]);
}
}
compareTriplets delivers a pointer to a int array.
Your score variable in your main method will therefore have to have the type int *. Meaning it is the pointer to the first int in the array.
#include<stdio.h>
int a[3];
int b[3];
int score[] = {0,0};
int *compareTriplets(int a[], int b[]);
int *compareTriplets(int a[], int b[])
{
int i;
for(i=0;i<3;i++)
{
if( a[i] > b[i])
{
score[0] += 1;
}
else if( b[i] > a[i])
{
score[1] += 1;
}
}
return score;
}
int main(int argc, char** argv)
{
a[0] = a[1] = a[2] = 1;
b[0] = b[1] = b[2] = 2;
int *score = compareTriplets(a,b);
printf("%d, %d\n", score[0], score[1]);
return 0;
}
To print it, we access the array elements by the [] operator.
However let me add, that having your score array be a global variable seems like the wrong decision here.
int *compareTriplets(const int a[], const int b[], int *score)
{
int i;
score[0] = 0; score[1] = 0;
for(i=0;i<3;i++)
{
if( a[i] > b[i])
{
score[0] += 1;
}
else if( b[i] > a[i])
{
score[1] += 1;
}
}
return score;
}
Usage:
int main(void)
{
int a[3] = {rand(), rand(), rand()};
int b[3] = {rand(), rand(), rand()};
int score[2];
compareTriplets(a,b,score);
printf("%d %d\n", score[0], score[1]);
}
or
struct score
{
int score[2];
};
struct score compareTriplets(const int a[], const int b[])
{
int i;
struct score sc = {0,0};
for(i=0;i<3;i++)
{
if( a[i] > b[i])
{
sc.score[0] += 1;
}
else if( b[i] > a[i])
{
sc.score[1] += 1;
}
}
return sc;
}
and usage"
int main(void)
{
int a[3] = {rand(), rand(), rand()};
int b[3] = {rand(), rand(), rand()};
struct score sc = compareTriplets(a,b);
printf("%d %d\n", sc.score[0], sc.score[1]);
}
Related
I tried to build a heap and finally print the elements in the form of an array.
Here it is the code (I know this doesn't really make sense but I just wanted to test my knowlwdge of heap and dynamic arrays):
#include <stdio.h>
#include <stdlib.h>
void heapiify(int *arr,int n, int i)
{
int largest=i;
int l=2*i+1; // left node
int r= 2*i+2; // right node
if(l<=n && *arr[l]>=*arr[i])
largest=l;
if (r <=n && *arr[r]<=*arr[i])
largest= r;
if(largest !=i)
{
int temp=*arr[i];
*arr[i]=*arr[largest];
*arr[largest]=temp;
}
heapify(*arr,n,largest);
}
void buildh(int *arr,int n,int r,int c)
{
int i;
for(i=n/2-1;i>=0;i--)
heapify(*arr,n,i);
output(*arr,r,c);
}
void output(int *arr,int r,int c)
{
int i,j;
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
{
printf("%d",*arr[i*c+j]);
}
printf("\n");
}
}
int main()
{
int i,j,r,c;
printf("enter the number of rows");
scanf("%d",&r);
printf("enter the number of columns");
scanf("%d",&c);
int n=r*c;
int *arr=malloc(n*sizeof(int));
for(i=0;i<r;i++)
{
for(j=0;j<c;j++)
scanf("%d",&arr[i*c+j]);
}
buildh(*arr,n,r,c);
}
I'm getting 9 errors which are all the same
invalid argument type of unary '*'( have int)
Your arr variable is of type pointer to int:
int *arr=malloc(n*sizeof(int));
So when you call buildh, which takes the same type, you have to pass it as-is:
buildh(arr,n,r,c);
Same for the other cases.
The problem is the dereference of arr, across your funtions in multiple places, and the passing of dereferenced *arr in your functions to int * parameters, you should pass arr, try:
//...
void heapify(int *arr, int n, int i)
{
int largest = i;
int l = 2 * i + 1; // left node
int r = 2 * i + 2; // right node
if (l <= n && arr[l] >= arr[i]) //here
largest = l;
if (r <= n && arr[r] <= arr[i]) //here
largest = r;
if (largest != i)
{
int temp = arr[i]; //here
arr[i] = arr[largest]; //here
arr[largest] = temp; //here
}
heapify(arr, n, largest); //here
}
void buildh(int *arr, int n, int r, int c)
{
int i;
for (i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i); //here
output(arr, r, c); //here
}
void output(int *arr, int r, int c)
{
int i, j;
for (i = 0; i < r; i++)
{
for (j = 0; j < c; j++)
{
printf("%d", arr[i * c + j]); //here
}
printf("\n");
}
}
int main()
{
//...
buildh(arr, n, r, c); //here
}
While trying to write a code to find the intersection of two arrays,I came across a problem. I can't seem to modify a pointer inside a function.
Inside my find_intersection I get the error while doing the realloc function,compiler states that "counter" has no arithmetic value.
Any explanation on what went wrong here?
#include <stdio.h>
#include <stdlib.h>
int quick_sort(int*, int, int);
void swap(int*, int*);
int partition(int *, int, int);
int input_array_dyn(int*n);
int *find_intersection(int*, int*, int*, int, int,int *);
main()
{
int size1, size2, *counter, i=0;
int *arr1 = input_array_dyn(&size1);
int *arr2 = input_array_dyn(&size2);
quick_sort(arr1, 0, size1 - 1);
quick_sort(arr2, 0, size2 - 1);
int *arr3 = (int*)calloc(size2, sizeof(int));
arr3= find_intersection(arr1, arr2, arr3, size1, size2, &counter);
printf("The size of the new array is:%d\n", counter);
while (i < counter)
{
printf("%d\n", arr3[i]);
i++;
}
free(arr1);
free(arr2);
free(arr3);
}
int *find_intersection(int *arr1, int *arr2, int *arr3, int SA, int SB, int *counter)
{
int i = 0, j = 0, n = 0;
*counter = 0;
while (i < SA &&j < SB)
{
if (arr1[i] < arr2[j])
i++;
else if (arr2[j] < arr1[i])
j++;
else
{
arr3[n] = arr1[i];
i++;
n++;
j++;
}
}
counter = n;
arr3 = (int*)realloc(arr3, counter*sizeof(int));/*error here*/
return arr3;
}
int input_array_dyn(int*n)
{
int i;
int *a;
printf("Enter the size of the array:\n");
scanf("%d", n);
a = (int*)calloc(*n, sizeof(double));
assert(a);
printf("Enter the array elements:%d.\n", *n);
for (i = 0; i < *n; i++)
scanf("%d", a + i);
return a;
}
void swap(int* a, int* b)
{
int t = *a;
*a = *b;
*b = t;
}
int partition(int *arr, int low, int high)
{
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
if (arr[j] <= pivot)
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
int quick_sort(int *arr, int low, int high)
{
if (low < high)
{
int pi = partition(arr, low, high);
quick_sort(arr, low, pi - 1);
quick_sort(arr, pi + 1, high);
}
}
In find_intersection() counter is a pointer to an int. To change it's value you need to use *counter instead of counter.
return arr3; attempts to return a pointer to int while function is declared to return just int. counter is a pointer to an int while you are using it as an regular int setting to 0 and so on.
I made maximum subarray algorithm, which something seems to be wrong with. Since C cannot return multiple values, function "maxarr" OR "maxcarr" is supposed to return three value-(start index, end index, and sum of it) in a static struct "rettype". However, those return value seems to be the same one(I have checked its memory adress, which was all same). I suppose that error occurs because static type variables are only declared once and do not be initialized more than one time, but I do not know how I can correct it.
#include <stdio.h>
#include <stdlib.h>
struct rettype
{
int a;
int b;
int c;
};
struct rettype* maxarr(int i, int j, int* array);
struct rettype* maxcarr(int i, int j, int* array);
int main(void)
{
int array[20];
int temp = 0;
int num = 0;
int len = 0;
struct rettype* ret;
printf("Type length in.\n");
scanf("%d", &len);
while (num<len)
{
printf("%dth element: ", num);
scanf("%d", &array[num]);
num++;
}
ret = maxarr(1, len, array);
printf("Maximum Subarray:\nfrom element %d to element %d with sum of %d\n", ret->a, ret->b, ret->c);
return 0;
}
struct rettype* maxarr(int i, int j, int* array)
{
static struct rettype retb;
static struct rettype ret;
struct rettype* fretr;
struct rettype* fretc;
struct rettype* fretl;
int hi=j;
int mid;
int low=i;
mid = ((hi + low) / 2);
if (i == j) {//base case
retb.a = i;
retb.b = j;
retb.c = *(array + i);
return &retb;
}
fretl = maxarr(i, mid, array);
fretr = maxarr(mid+1, j, array);
fretc = maxcarr(i, j, array);
if (fretl->c>fretr->c && fretl->c>fretc->c)
{
ret.a = fretl->a;
ret.b = fretl->b;
ret.c = fretl->c;
return &ret;
}
else if (fretr->c>fretl->c && fretr->c>fretc->c)
{
ret.a = fretr->a;
ret.b = fretr->b;
ret.c = fretr->c;
return &ret;
}
else
{
ret.a = fretc->a;
ret.b = fretc->b;
ret.c = fretc->c;
return &ret;
}
}
struct rettype* maxcarr(int i, int j, int* array)
{
int mid = (i + j) / 2;
static struct rettype ret;
int a = mid;
int b = mid+1;
int risum = -9999;
int lesum = -9999;
int sum = 0;
while (a-->i)
{
sum += *(array + a);
if (sum>lesum)
{
lesum = sum;
}
}
sum = 0;
while (b++<j)
{
sum += *(array + b);
if (sum>risum)
{
risum = sum;
}
}
sum = 0;
ret.a = a;
ret.b = b;
ret.c = risum + lesum;
return &ret;
}
you're using a static variable you're taking the address from to return to the caller.
In that case, you're sharing a same memory area for your return value, instead of creating separate ones.
Why not returning the value of the structure instead (C cannot return arrays, but can return structs, fortunately):
struct rettype maxcarr(int i, int j, int* array)
{
int mid = (i + j) / 2;
struct rettype ret;
...
return ret;
}
(and drop static for an auto variable which is copied when returned)
Note that you'll have to apply this pattern to all your routines.
Maximum subarray problem
Kadane's algorithm
#include <stdio.h>
struct rettype {
int start;
int end;
int sum;
};
struct rettype max_subarray(int array[], int length);
int main(void){
int array[20];
int len = 0, num;
struct rettype ret;
printf("Type length in.\n");
if(scanf("%d", &len) != 1){
printf("invalid input.\n");
return 1;
}
if(len > 20){
printf("too long.\n");
return 2;
}
for(num = 0; num < len; num++){
printf("%dth element: ", num);
if(scanf("%d", &array[num]) != 1){
printf("invalid input.\n");
len = num;
break;
}
}
if(len > 0){
ret = max_subarray(array, len);
printf("Maximum Subarray:\nfrom element %d to element %d with sum of %d\n", ret.start, ret.end, ret.sum);
}
return 0;
}
struct rettype max_subarray(int array[], int length){
struct rettype ret = { .sum = array[0] };
struct rettype curr = { .sum = array[0] };
for(int i = 1; i < length; ++i){
if(array[i] < array[i] + curr.sum){
curr.sum += array[i];
curr.end = i;
} else {
curr.sum = array[i];
curr.start = curr.end = i;
}
if(ret.sum < curr.sum){
ret = curr;
}
}
return ret;
}
The following code is trying to find the averages of a set of numbers in C, but the median and the mean both do not return anything. How do I make it so the mean and the median both return a float? Am I returning an invalid value or?
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
float mean(int arr[], int size){
int sum = 0;
for(int i = 0; i<size; i++){
sum += arr[i];
}
return ((float)sum/size);
}
int range(int arr[], int size){
int smallest = arr[0];
int largest = arr[0];
for(int i=0; i<size; i++){
if(smallest>arr[i]){
smallest = arr[i];
} if(largest<arr[i]){
largest = arr[i];
}
} int difference = largest - smallest;
return difference;
}
int mode(int arr[], int size){
int maxValue = 0;
int maxCount = 0;
for(int i = 0; i<size; i++){
int count = 0;
for(int j = 0; j<size; j++){
if(arr[j] == arr[i]){
count++;
}
} if(count > maxCount){
maxCount = count;
maxValue = arr[i];
}
} return maxValue;
}
float median(int arr[], int size){
qsort(arr, size, sizeof(int), compare);
float middleOfArray = size/2;
int roundedMiddleOfArray = rint(middleOfArray);
if(ceilf(middleOfArray) == middleOfArray){
return((float)arr[roundedMiddleOfArray]);
}
else{
return((float)arr[roundedMiddleOfArray] - arr[roundedMiddleOfArray-1]);
}
}
int main(){
int array[6] = {1,2,3,4,5,6};
int newMean = mean(array, 5);
int newRange = range(array, 5);
int newMode = mode(array,5);
int newMedian = median(array, 5);
printf("The mean is : %f \n", newMean);
printf("The range is : %d \n",newRange);
printf("The mode is : %d \n",newMode);
printf("The median is : %f \n", newMedian);
return 0;
}
Turns out the way you fix it is by declaring the mean and the median as floats not ints (in main).
so i get two parameters, one is N [ how big the array would be] and nr_vals [ this is the range, if nr_vals == 2, then range would be ( 0~1)]. I'm getting an error in swap function EXC_BAD_ACCESS. and the permutations are not printing right. any ideas?
My Swap Function ;
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
Main fun;
void perm_rec_1(int N, int nr_vals){
int array[N];
int tempAr = 0;
for (int arrayFiller = 0; arrayFiller <= N; arrayFiller++)
{
if (arrayFiller == nr_vals){
tempAr = 0;
}
array[arrayFiller] = tempAr;
tempAr++;
}
prem_rec_help(N, nr_vals, array);
}
Secondary;
void prem_rec_help(int N, int nr_vals, int array[])
{
int tempArray[N];
copy_array(array, tempArray, N);
show(tempArray, N);
int M = 0;
int solid = N;
last_helper(tempArray, array, M, N, solid, nr_vals);
}
Recursive Function;
void last_helper(int array[],int temp[], int M, int N, int soild, int nr_vals ){
if (M != N)
{
last_helper(array,temp, M+1, N, soild, nr_vals);
}
for ( int i = 0; i < nr_vals; i++)
{
temp[M] = i;
show(temp, soild);
}
M--;
if(M == 0)
{
for( int swaper = 0; swaper <= soild; swaper++)
{
swap(array[swaper], array[swaper+1]);
copy_array(array, temp, soild);
if(swaper == soild)
{
return;
}else{
last_helper(array,temp, M, N, soild, nr_vals);
}
}
}
}