I have been solving a problem of CyclicRotation. This is my code:
#include<stdio.h>
#include<stdlib.h>
struct Results{
int *A;
int N;
};
struct Results solution(int A[], int N, int K){
struct Results result;
int *tab, i=0, j=0;
tab = (int*) malloc(N*sizeof(int));
if(N==0){
result.A = A;
result.N = N;
return result;
}
if(K>N){
K = K % N;
}
if(K<N && N != 0){
for(i=N-K;i<N;i++){
tab[j] = A[i];
j = j + 1;
}
i = 0;
while(i<N-K){
tab[j] = A[i];
i++;
j++;
}
} else {
tab = A;
}
result.A = tab;
result.N = N;
return result;
}
int main()
{
int j[]={2,3,4,5,6,7,8};
int mylen;
int myk = 3;
mylen = sizeof(j)/sizeof(j[0]);
return 0;
}
I tried this in the code:
int main()
{
int j[]={2,3,4,5,6,7,8};
int mylen;
int myk = 3;
mylen = sizeof(j)/sizeof(j[0]);
printf("The result is %d",solution(j,mylen,myk).A);
return 0;
}
The expected result is 6782345, but the result in the console is different:
The result is -591373584
I'm not sure if the array printing is correct (given that is an array, perhaps I need a loop?). Please, could you give me a help? Thank you in advance.
int main()
{
int j[]={2,3,4,5,6,7,8};
int mylen;
int myk = 3;
mylen = sizeof(j)/sizeof(j[0]);
struct Results results = solution(j, mylen, myk);
for(int i = 0; i < mylen; i++)
printf("%d\n", results.A[i]);
free(results.A);
return 0;
}
Related
I'm completely new with MPI, and I have to solve a problem: I have 2 1D arrays (A and B), which I have to sum the contents of, and store the result in a different array (C). I've done an example using just one array, in which I sum all the contents of, then returning the result.
How can I adapt this with Gather and Scatter?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"mpi.h"
#define N 10
int* CreaArreglo(tam){
int* arr;
arr = (int*)malloc(tam*sizeof(int));
return arr;
}
int* GeneraArreglo(int tam){
int* arr;
arr = (int*)malloc(tam*sizeof(int));
int i;
srand(time(0));
for(i = 0; i < tam ; i++)
{
arr[i]=rand()%40;
}
return arr;
}
int main(int argc,char*argv[])
{
MPI_Status status;
int idProc , numProc;
MPI_Init(&argc,&argv);
MPI_Comm_rank(MPI_COMM_WORLD,&idProc);
MPI_Comm_size(MPI_COMM_WORLD,&numProc);
int nDatos = N/(numProc-1);
int nDatosU = nDatos + (N%(numProc-1));
if(idProc == 0){
int* A;
A = GeneraArreglo(N);
int i;
for(i=1;i <= numProc-2;i++){
MPI_Send(A+((i-1)*nDatos),nDatos,MPI_INT,i,0,MPI_COMM_WORLD);
}
MPI_Send(A+((i-1)*nDatos),nDatosU,MPI_INT,i,0,MPI_COMM_WORLD);
int suma = 0;
int sumap = 0;
i = 1;
do{
MPI_Recv(&sumap,1,MPI_INT,i,0,MPI_COMM_WORLD,&status);
suma += sumap;
i++;
}while(i<(numProc));
printf("suma total = %d \n",suma);
}
else{
if(idProc == numProc-1){
nDatos = nDatosU;
}
int suma = 0;
int i=0 ;
int* A = CreaArreglo(nDatos);
MPI_Recv(A,nDatos,MPI_INT,0,0,MPI_COMM_WORLD,&status);
i=0;
do{
printf("%d +",A[i]);
suma += A[i];
i++;
}while(i<(nDatos));
MPI_Send(&suma,1,MPI_INT,0,0,MPI_COMM_WORLD);
}
MPI_Finalize();
}
#include <stdio.h>
#include <stdlib.h>
int *squares(int max_val) {
int *result = malloc(max_val * sizeof(int));
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return(result);
}
int main() {
int *sq = squares(10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return(0);
}
Basically take's an integer and returns a integer array of its squares. (Above works)
How would I do this without malloc or pointers?
#include <stdio.h>
#include <stdlib.h>
int[] squares(int max_val) {
int result[max_val];
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return(result);
}
int main() {
int sq[] = squares(10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return(0);
}
Above errors because of the function call. Is this possible? Or do we have to do it with pointers?
How about something like this.. ?
#include <stdio.h>
#include <stdlib.h>
void squares(int values[], int max_val) {
for(int i = 1; i <= max_val; i++) {
values[i - 1] = i * i;
}
}
int main() {
int sq[10];
squares(sq, 10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return(0);
}
This
int[] squares(int max_val) {
int result[max_val];
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return(result);
}
is not valid C:
a.c:3:4: error: expected identifier or ‘(’ before ‘[’ token
int[] squares(int max_val)
It should be
int *squares(int max_val) {
...
}
Putting that aside, your second squares returns a pointer to a local array.
This array ceases to exist once squares ends it's execution, so you are
returning an pointer that become invalid the moment it returns.
Also
int sq[] = squares(10);
is invalid C as well
a.c:9:13: error: invalid initializer
int sq[] = squares(10);
^~~~~~~
you cannot assign a function value to an array. The correct
version is
int *sq = squares(10);
So, if you don't want squares to allocate memory with malloc for the result, then you can
either allocate the memory in main or create an array in main and pass it to
squares:
int squares(int *result, int max_val) {
if(result == NULL || max_val <= 0)
return 0;
int i;
for(i = 1; i <= max_val; i++) {
result[i-1] = i*i;
}
return 1;
}
// version 1
int main() {
int *sq = malloc(10 * sizeof *sq);
// NEVER forget to check the return value of malloc
if(sq == NULL)
{
fprintf(stderr, "not enough memory\n");
return 1;
}
squares(sq, 10);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
free(sq); // NEVER forget to free
return 0;
}
// version 2
int main() {
int sq[10];
squares(sq, sizeof sq / sizeof sq[0]);
int i;
for(i = 0; i < 10; i++) {
printf("%d\t", sq[i]);
}
printf("\n");
return 0;
}
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;
}
I am trying to access a structure with a pointer to an integer , from main. But the program crashes. It needs to be built with "std=c99" option as it is the requirement in a test.
The code is as follows:
#include <stdio.h>
#include <malloc.h>
struct Results{
int *A;
int N;
};
struct Results solution(int A[], int N, int K) {
struct Results result;
// write your code in C99 (gcc 4.8.2)
int* T = (int*) malloc(N*sizeof(int));
result.A = A;
result.N = N;
int count = 0;
while(count < K)
{
for(int i = 0; i < N; i++)
{
if(i > 0)
{
T[i] = A[i-1];
}
else
{
T[0] = A[N-1];
}
}
count++;
for(int i = 0; i < N; i++)
{
A[i] = T[i];
}
};
for(int i = 0;i < N; i++)
{
A[i] = T[i];
}
return result;
}
struct Results solution(int A[], int N, int K);
void main()
{
int B[5] = {3,8,9,7,6};
struct Results st;
solution(B,sizeof(B),1);
}
The trouble is at line:
" solution(B,sizeof(B),1);"
What am I doing wrong?
Please help.
You see sizeof(B) would give the number of elements in B times the size of an int, use sizeof(B) / sizeof(B[0]) instead.
I am implementing Mergesort using the algorithm described in "Introduction to Algorithms". However, upon every execution I get a garbage value as the first element of the sorted array. Here is the code for it:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void mergesort(int a[], int p, int r);
void merge(int a[], int p, int q, int r)
{
int *left, *right;
int i,j,k,l,n1,n2;
n1 = q-p+1;
n2 = r-q;
left = malloc(sizeof(int)*(n1+1));
right = malloc(sizeof(int)*(n2+1));
for ( i = 0; i < n1; i++) {
left[i] = a[p+i];
}
for ( j = 0; j < n2; j++) {
right[j] = a[q+j+1];
}
left[n1] = INT_MAX;
right[n2] = INT_MAX;
i = 0;
j = 0;
for ( k = p; k <= r; k++) {
if (left[i] <= right[j]) {
a[k] = left[i];
i++;
}
else {
a[k] = right[j];
j++;
}
}
free(left);
free(right);
return ;
}
int main(int argc, char* argv[])
{
int i;
int a[] = {5,2,4,7,1,3,2,6} ;
mergesort(a,0,sizeof(a)/sizeof(int));
for ( i = 0; i < sizeof(a)/sizeof(int); i++) {
printf("%d\n",a[i]);
}
return 0;
}
void mergesort(int a[], int p, int r)
{
if (p < r) {
int q;
q = (p+r)/2 ;
mergesort(a,p,q);
mergesort(a,q+1,r);
merge(a,p,q,r);
}
}
It looks like you have not clearly defined the meanings of the mergesort parameters. Here, your last element is positioned one past the end of the array:
mergesort(a,0,sizeof(a)/sizeof(int));
But here,
mergesort(a,p,q);
mergesort(a,q+1,r);
Q seems to be over the last element in the array. If your code follows the first, you will be forgetting to actually sort the value q. If it follows the second, you will be attempting to sort a garbage value one past the end of the array.
Shouldn't
mergesort(a,0,sizeof(a)/sizeof(int));
be
mergesort(a,0,sizeof(a)/sizeof(int)-1);
?
Considering you do
n1 = q-p+1;
etc.
There is almost certainly an off-by-one error somewhere in here.
You must chose if you want to include a[r] or not. Here your choice is not consistent hence the error.
Here is a good code (I don't include a[r]):
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void mergesort(int a[], int p, int r);
void merge(int a[], int p, int q, int r)
{
int *left, *right;
int i,j,k,l,n1,n2;
n1 = q-p;
n2 = r-q;
left = malloc(sizeof(int)*(n1+1));
right = malloc(sizeof(int)*(n2+1));
for ( i = 0; i < n1; i++) {
left[i] = a[p+i];
}
for ( j = 0; j < n2; j++) {
right[j] = a[q+j];
}
left[n1] = INT_MAX;
right[n2] = INT_MAX;
i = 0;
j = 0;
for ( k = p; k < r; k++) {
if (left[i] <= right[j]) {
a[k] = left[i];
i++;
}
else {
a[k] = right[j];
j++;
}
}
free(left);
free(right);
return ;
}
int main(int argc, char* argv[])
{
int i;
int a[] = {5,2,4,7,1,3,2,6} ;
mergesort(a,0,sizeof(a)/sizeof(int));
for ( i = 0; i < sizeof(a)/sizeof(int); i++) {
printf("%d\n",a[i]);
}
return 0;
}
void mergesort(int a[], int p, int r)
{
if (r-p > 1) {
int q;
q = (p+r)/2 ;
mergesort(a,p,q);
mergesort(a,q,r);
merge(a,p,q,r);
}
}