Reading Sparse Matrix from Binary File in C - c

Firstly, I am sorry for my English.
I am trying to read an integer array which represents some sparse matrix from a binary and I have to print this matrix.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 20
//on this way i have written the matrix in the binary
typedef struct{
int lin,col;
double val;
}termen;
typedef struct{
int nl,nc,nn;
termen* term;
}sparse_matrix;
void afisare_mat(sparse_matrix m){
int i,j,k = 0;
for(i = 0; i < m.nl; i++){
for(j = 0; j < m.nc; j++){
if(i == m.term[k].lin && j == m.term[k].col){
printf("%3.2lf ",m.term[k].val);
k++;
}else{
printf("%d ",0);
}
}printf("\n");
}
}
int main(){
/*this is the code used for write in the binary file
//i tried to print these values and seems to be ok
sparse_matrix m1,m2,m3;
m1.term = malloc(2*sizeof(termen));
m1.nl = 3;
m1.nc = 3;
m1.nn = 2;
m1.term[0].lin = 0;
m1.term[0].col = 1;
m1.term[0].val = 3.2;
m1.term[1].lin = 1;
m1.term[1].col = 2;
m1.term[1].val = 5.6;
afisare_mat(m1);
m2.term = malloc(3*sizeof(termen));
m2.nl = 4;
m2.nc = 4;
m2.nn = 3;
m2.term[0].lin = 0;
m2.term[0].col = 0;
m2.term[0].val = 1.9;
m2.term[1].lin = 1;
m2.term[1].col = 2;
m2.term[1].val = 0.5;
m2.term[2].lin = 2;
m2.term[2].col = 3;
m2.term[2].val = 6.960;
afisare_mat(m2);
m3.term = malloc(1*sizeof(termen));
m3.nl = 3;
m3.nc = 3;
m3.nn = 1;
m3.term[0].lin = 1;
m3.term[0].col = 2;
m3.term[0].val = 6.75;7
afisare_mat(m3);
FILE *f = fopen("in.bin","wb");
fwrite(&m1,sizeof(sparse_matrix),1,f);
fwrite(&m2,sizeof(sparse_matrix),1,f);
fwrite(&m3,sizeof(sparse_matrix),1,f);
fclose(f);
*/
FILE *f = fopen("in.bin","rb");
int n, v[10], i, j, k,nr = 0,it; //n=number of matrix asked, v=array with
//number(s)(<= n) of matrix which have to print
scanf("%d",&n);
sparse_matrix m;
while(fread(&k,sizeof(int),1,f) > 0){
fseek(f,2*sizeof(int),SEEK_CUR);
fseek(f,sizeof(termen*),SEEK_CUR);
nr++;
}
for(i = 0; i < n; i++){
scanf("%d",&v[i]);
if(v[i] > nr)
printf("That matrix not exist\n");
}
fseek(f,0,0);
j = 0;
while(fread(&k,sizeof(int),1,f) > 0){ //citesc nl din fiecare matrice
for(i = 0; i < n; i++){
if(j == v[i]){ //number of matrix which i read;
//print matrix
m.nl = k;
fread(&m.nc,sizeof(int),1,f);
fread(&m.nn,sizeof(int),1,f);
m.term = malloc(m.nn*sizeof(termen));
fread(m.term,sizeof(termen),m.nn,f);
afisare_mat(m);
free(m.term);
fseek(f,(j+1)*sizeof(sparse_matrix),0);
}
}j++;
}
fclose(f);
return 0;
}
This code prints on my screen the form of matrix but full of zeroes. I think that the rest of the elements (!= 0) aren't read ok from the binary file. Can you help me, please?

Related

I am trying to write a simple tsp question but meet some problems

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define max 100
void tsp(int Dis[max][max],int v[],int N,int count,int currPos,int cost,int ans){
/*for(j=1;j<N+1;j++){
if(visited[j]==0){
sum+=Dis[i][j];
visited[j] = 1;
DFS(visited,j,Dis,sum);
}
}*/
if(count == N&&Dis[1][currPos]>0){
if(ans> cost+Dis[1][currPos]) ans = cost+Dis[1][currPos];
//ans = min(ans,cost + Dis[1][currPos]);
return;
}
for (int i = 0;i<N+1;i++){
if(v[i]==0&&Dis[currPos][i]>0){
v[i] = 1;
tsp(Dis,v,N,count + 1,cost + Dis[currPos][i],ans);
v[i] = 0;
}
}
};
int main(int argc, char const *argv[])
{
int N;
int size = 1;
int count = 1;
char x[100] = {0};
FILE *fp=fopen(argv[1],"r");
if(fp==NULL){
printf("Cannot open the file,strike any key to exit!\n");
getchar();
exit(0);
}
for (int i = 0;!feof(fp);i++){
fscanf(fp,"%hhd",&x[i]);
}
N=x[0];
int Dis[N][N], City[N];
for(int i=1;i<N;i++){
size=size*i;
}
char y[size];
for (int i=1;i<size+1;i++){
y[i] = x[i];
//printf("%d\n",y[i]);
}
for(int i=2; i < N + 1; i++){
for(int j=1; j < i ; j++){
Dis[j][i] = y[count];
Dis[i][j] = y[count];
count+=1;
printf("(%d,%d),(%d,%d)",j,i,i,j);
printf("%d\n",Dis[j][i]);
}
}
for(int i=0;i<N;i++){
City[i]=i + 1;//create the number of city with 1 ...... N
}
int curr_constraint = 0;
int v[N+1];
for (int i = 1; i < N+1; i++){
v[i] = 0;
}
for(int i = 1;i<N+1;i++){
curr_constraint += Dis[i][i+1];
}
v[1]= 1;
int ans = INT_MAX;
printf("The orginal constraint is %d\n",curr_constraint);
tsp(Dis[N][N],v,N,0,1,0,ans);
return 0;
}
The question asks me to implement a tsp question which always starts with the number 1 city, it will read the data including the numbers of nodes and length between two citys from a txt file in the position of argv[1]. And then find the smallest way for all city without going back the first city.
The file is like following:
4
5
40 9
11 6 8
which means:
the number of citys N = 4
Distance: d[1][2] = 5, d[1][3] = 40, d[2][3] = 9, d[1][4] = 11, d[2][4] = 6, d[3][4] = 8.
I want to create a array including the distance in tsp function, but the lenght I read only in the main function. How to solve this problem?

My program doesn't deal cards correctly after the first round

I have a program that has to go until one of the players get 30 points, if I play it only 1 round it works perfectly but when I try to deal the cards again (different cards per round) it deals the last card it gave the round before and the other 2 are the same (sometimes it doesn't even deal them).
while (Player1Point != 30 && Player2Point != 30){
for (int i = CardCount; i < Count; i++){
DealCard(Deck, i, &Hand1, &Hand2, Count, j);
j++;
}
Count = Count + 4;
CardCount = CardCount + 4;
Here's the function DealCard:
void DealCard(int Deck[CARDS][PLAYERS], int i, int Hand1[NUMBER][SUITS], int Hand2[NUMBER][SUITS], int Count, int j){
if (i < Count && j < 3){
Hand1[j][0] = Deck[i][0];
Hand1[j][1] = Deck[i][1];
Hand2[j][0] = Deck[i+3][0];
Hand2[j][1] = Deck[i+3][1];
}
}
The arrays I use for the cards:
char* suit[SUITS] = {"Espada", "Oro", "Copa", "Basto"};
char* num[NUMBER] = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "diez", "once", "doce"};
When i try to deal for the second time it gives me the last card and 2 "uno de Espada" or 2 "uno de (null)"
EDIT:
The MRE (still 66 lines)
#include <stdio.h>
#include <time.h>
#include <string.h>
#define SUITS 4
#define NUMBER 10
#define CARDS 40
#define PLAYERS 3
char* suit[SUITS] = {"Espada", "Oro", "Copa", "Basto"};
char* num[NUMBER] = {"uno", "dos", "tres", "cuatro", "cinco", "seis", "siete", "diez", "once", "doce"};
int main(){
int Player2Point = 0, Player1Point = 0, CardCount = 0, j = 0, Count = 3;
int Deck[CARDS][PLAYERS];
int Hand1[NUMBER][SUITS];
int Hand2[NUMBER][SUITS];
srand(time(0));
InitDeck(Deck);
ShuffleDeck(Deck);
while (Player1Point != 30 && Player2Point != 30){
for (int i = CardCount; i < Count; i++){
DealCard(Deck, i, &Hand1, &Hand2, Count, j);
j++;
}
PrintCard(Hand1, 3);
Count = Count + 4;
CardCount = CardCount + 4;
Player1Point++;
}
return 0;
}
void InitDeck(int Deck[CARDS][PLAYERS]){
int suit, num, row;
row = 0;
for (suit = 0; suit < 4; suit++){
for (num = 0; num < 10; num++){
Deck[row][0] = suit;
Deck[row][1] = num;
row++;
}
}
}
void ShuffleDeck(int Deck[CARDS][PLAYERS]){
int Src, Dest, i;
for(i = 0; i < CARDS; i++){
Src = i;
Dest = rand()%CARDS;
SwapCards(Deck, i, Dest);
}
}
void SwapCards(int Deck[CARDS][PLAYERS], int Src, int Dest){
int Temp;
Temp = Deck[Dest][0];
Deck[Dest][0] = Deck[Src][0];
Deck[Src][0] = Temp;
Temp = Deck[Dest][1];
Deck[Dest][1] = Deck[Src][1];
Deck[Src][1] = Temp;
}
void DealCard(int Deck[CARDS][PLAYERS], int i, int Hand1[NUMBER][SUITS], int Hand2[NUMBER][SUITS], int Count, int j){
if (i < Count && j < 3){
Hand1[j][0] = Deck[i][0];
Hand1[j][1] = Deck[i][1];
Hand2[j][0] = Deck[i+3][0];
Hand2[j][1] = Deck[i+3][1];
}
}
void PrintCard(int Hand1[NUMBER][SUITS], int size){
printf("Your cards: \n");
int psuit, pnum;
for (int i = 0; i < size; i++){
psuit = Hand1[i][0];
pnum = Hand1[i][1];
printf("Card: %s de %s\n", num[pnum], suit[psuit]);
}
printf("\n");
}

C code counting occurrences in Matrix using sub matrices and MPI Parallelization

I have an assignment to take in a 16 by 16 array of random numbers between 0-31 from a text file. I have been able to read in the matrix and allocate it to a 2D array called arr1. Now I need to use MPI to make my code work when parallelized over 1,4,8,16,32 cores per processor. Can someone show me how to weave in the MPI calls to split up the large matrix into varying sizes of submatrices depending on number of processors? Then use MPI to send, receive, etc. I want each node to count the occurrences of its sub matrix and the root node to combine them all and print out final tally.
//#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int MAXR,MAXC;
MAXR= 16; MAXC=16;
int arr1[MAXR][MAXC],i,j;
FILE *fp;
fp =fopen("arrays16.txt","r");
for(i=0;i<MAXR;i++) // this loop takes the information from .txt file and puts it into arr1 matrix
{
for(j=0;j<MAXC;j++)
{
fscanf(fp,"%d\t",&arr1[i][j]);
}
}
for(i=0;i<MAXR;i++)
{
printf("\n");
for(j=0;j<MAXC;j++)
printf("%d\t",arr1[i][j]);
}
printf("\n\n");
//printf("%d\t",arr1[1][2]);
int occurrences[3][33] = {{0}};
occurrences[0][0] = 0;
occurrences[0][1] = 1;
occurrences[0][2] = 2;
occurrences[0][3] = 3;
occurrences[0][4] = 4;
occurrences[0][5] = 5;
occurrences[0][6] = 6;
occurrences[0][7] = 7;
occurrences[0][8] = 8;
occurrences[0][9] = 9;
occurrences[0][10] = 10;
occurrences[0][11] = 11;
occurrences[0][12] = 12;
occurrences[0][13] = 13;
occurrences[0][14] = 14;
occurrences[0][15] = 15;
occurrences[0][16] = 16;
occurrences[0][17] = 17;
occurrences[0][18] = 18;
occurrences[0][19] = 19;
occurrences[0][20] = 20;
occurrences[0][21] = 21;
occurrences[0][22] = 22;
occurrences[0][23] = 23;
occurrences[0][24] = 24;
occurrences[0][25] = 25;
occurrences[0][26] = 26;
occurrences[0][27] = 27;
occurrences[0][28] = 28;
occurrences[0][29] = 29;
occurrences[0][30] = 30;
occurrences[0][31] = 31;
// for(j=1;j<33;j++)
//{
// printf("%d",occurrences[1][j]);
// }
//printf("\n\n");
int k;
int count;
for(k=0; k <= 31; k++) {
count = 0;
for (i=0; i<= MAXR-1; i++) {
for(j=0;j<=MAXC-1;j++) {
if(arr1[i][j] == occurrences[0][k]) {
count++;
occurrences[1][k] = count;
printf("Occurrences of %d = , are equal to = %d\n",arr1[i][j], occurrences[1][k]);
//break;
}
else {
}
}
}
}
for(i=0;i<1;i++)
{
printf("\n");
for(j=0;j<32;j++)
printf("%d\t",occurrences[i][j]);
}
for(i=1;i<2; i++)
{
printf("\n\n");
for(j=0;j<=32;j++)
printf("%d\t",occurrences[i][j]);
}
}

C struct invalid type argument of '->' in Bankers Algorithm

I am relatively new to C and I am trying to get my Bankers Algorithm to work below. The logic is solid, but I am getting compilation errors that I can't quite work out. The main one is dealing with my struct that holds all of the consumers data for the algorithm. It reads:
"error: invalid type argument of ‘->’ (have ‘struct threadData’)
t->allocation[t->customer_num][i] = t->allocation[t->customer_num][i] - t->requestOrRelease[i];"
That is one of many similar errors.
I know you may find more, since I am not done yet, so if you do, shout them out.
I have been working on this forever and I am stuck. Any help would be awesome. Keep in mind, I know there are things I may not be doing the best possible, but I want my code below to work and then I will optimize.
I know the code is lengthy, but I greatly appreciate any help. Thank you!
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <time.h>
#include <stdbool.h>
#define cust 5
#define reso 3
struct threadData
{
int available[reso];
int maximum[cust][reso];
int allocation[cust][reso];
int need[cust][reso];
int requestOrRelease[reso];
int customer_num;
} ;
void request_resources(struct threadData *t);
void release_resources(struct threadData *t);
int isSafeState(int work[],int need[][cust],int allocation[][cust]);
int sumVector(int input[]);
int sumRowCol(int input[][cust],int index,char c);
void fillRequestRelease(int * array,int max0,int max1,int max2);
int main(int argc, const char **argv)
{
int available[reso]; //number of resources available of each type
int maximum[cust][reso]; //maximum demand of each process
int allocation[cust][reso]; //number of resources of each type currently allocated
int need[cust][reso]; //remaining resouce needs of each process : maximum-allocation
pthread_mutex_t mutex;
pthread_mutex_init(&mutex,NULL); //Create mutex lock
bool end = false;
//===========================================
srand(time(NULL));
int i,j,r;
for(i = 0;i < argc;i++) //Initialize values in available array
{
r = atoi(argv[i]);
available[i] = r;
}
for(i = 0;i < cust;i++) //Initialize values in maximum array
{
for(j = 0;j < reso;j++)
{
r = rand()%8; //Random int between 0 and 7
reso[i][j] = r;
}
}
for(i = 0;i < cust;i++) //Initialize values in allocation/need arrays
{
for(j = 0;j < reso;j++)
{
allocation[i][j] = 0;
need[i][j] = 0;
}
}
//===========================================
threadData data;
data.available = available;
data.maximum = maximum;
data.allocation = allocation;
data.need = need;
data.requestOrRelease = requestOrRelease;
data.customer_num = 0;
pthread_t custRequest0,custRequest1,custRequest2,custRequest3,custRequest4;
pthread_t custRelease0,custRelease1,custRelease2,custRelease3,custRelease4;
while(true)
{
data.customer_num = 0;
fillRequestRelease(data.requestOrRelease,data.need[0][0],data.need[0][1],data.need[0][2]);
pthread_create(&custRequest0,NULL,(void *)data);
data.customer_num = 1;
fillRequestRelease(data.requestOrRelease,data.need[1][0],data.need[1][1],data.need[1][2]);
pthread_create(&custRequest1,NULL,(void *)data);
data.customer_num = 2;
fillRequestRelease(data.requestOrRelease,data.need[2][0],data.need[2][1],data.need[2][2]);
pthread_create(&custRequest2,NULL,(void *)data);
data.customer_num = 3;
fillRequestRelease(data.requestOrRelease,data.need[3][0],data.need[3][1],data.need[3][2]);
pthread_create(&custRequest3,NULL,(void *)data);
data.customer_num = 4;
fillRequestRelease(data.requestOrRelease,data.need[4][0],data.need[4][1],data.need[4][2]);
pthread_create(&custRequest4,NULL,(void *)data);
pthread_join(custRequest0,NULL);
pthread_join(custRequest1,NULL);
pthread_join(custRequest2,NULL);
pthread_join(custRequest3,NULL);
pthread_join(custRequest4,NULL);
data.customer_num = 0;
fillRequestRelease(data.requestOrRelease,data.allocation[0][0],data.allocation[0][1],data.allocation[0][2]);
pthread_create(&custRelease0,NULL,(void *)data);
data.customer_num = 1;
fillRequestRelease(data.requestOrRelease,data.allocation[1][0],data.allocation[1][1],data.allocation[1][2]);
pthread_create(&custRelease1,NULL,(void *)data);
data.customer_num = 2;
fillRequestRelease(data.requestOrRelease,data.allocation[2][0],data.need[2][1],data.need[2][2]);
pthread_create(&custRelease2,NULL,(void *)data);
data.customer_num = 3;
fillRequestRelease(data.requestOrRelease,data.allocation[3][0],data.allocation[3][1],data.allocation[3][2]);
pthread_create(&custRelease3,NULL,(void *)data);
data.customer_num = 4;
fillRequestRelease(data.requestOrRelease,data.allocation[4][0],data.allocation[4][1],data.allocation[4][2]);
pthread_create(&custRelease4,NULL,(void *)data);
pthread_join(custRelease0,NULL);
pthread_join(custRelease1,NULL);
pthread_join(custRelease2,NULL);
pthread_join(custRelease3,NULL);
pthread_join(custRelease4,NULL);
int nonZeroCount = 0;
for(i = 0;i < cust;i++)
{
for(j = 0;j < reso;j++)
{
if(need[i][j] > 0)
nonZeroCount++;
}
}
if(nonZeroCount == 0)
break;
}
printf("Program done!")
}
//Determines if system is in safe state
//Returns 0 if in safe state, else -1
int isSafeState(int work[],int need[][cust],int allocation[][cust]) //work = available
{
int i,j;
int temp1,temp2,trueCount,notSafeCount;
bool finish[sizeof(need)/sizeof(int)];
for (i = 0;i < sizeof(need)/sizeof(int);i++)
finish[i] = false;
trueCount = 0;
bool iexists = false;
while(true)
{
for(i = 0;i < sizeof(finish)/sizeof(int);i++)
{
temp1 = sumRowCol(need,i,'r');
temp2 = sumRowCol(work,0,'r');
if(finish[i] == false && (temp1 <= temp2))
{
finish[i] = true;
for(j = 0;j < reso;j++)
work[j] = work[j] + allocation[i][j];
trueCount++;
iexists = true;
}
}
if(trueCount == sizeof(finish)/sizeof(int))
return 0;
else if(iexists == false)
return -1;
}
}
// Returns sum of given vector
int sumVector(int input[])
{
int sum = 0;
int i;
for(i = 0;i < sizeof(input)/sizeof(int);i++)
sum += input[i];
return sum;
}
//Returns sum of given input array row/column
int sumRowCol(int input[][cust],int index,char c)
{
int sum = 0;
int i;
if(c == 'r')
{
for(i = 0;i < sizeof(input)/sizeof(int);i++)
sum += input[index][i];
}
else
{
for(i = 0;i < sizeof(input)/sizeof(int);i++)
sum += input[i][index];=
}
return sum;
}
void request_resources(struct threadData t)
{
int i,j,safeState,custNum;
int tempAvailable[reso];
int tempMaximum[cust][reso];
int tempAllocation[cust][reso];
int tempNeed[cust][reso];
int tempRequest[reso];
bool end = false;
if(t->requestOrRelease[0] == 0 && t->requestOrRelease[1] == 0 && t->requestOrRelease[2] == 0)
return;
while(true)
{
custNum = t->customer_num;
for(int i = 0;i < reso;i++)
{
if(t->requestOrRelease[i] > t->need[custNum][i])
{
printf("Error: Request is greater than need. Aborting request to bank.");
pthread_mutex_unlock(&mutex);
return;
}
}
int passCount;
while(true)
{
passCount = 0;
for(int i = 0;i < reso;i++)
{
if(t->requestOrRelease[i] > t->available[i])
{
passCount--;
while(true)
{
if(t->requestOrRelease[i] <= t->available[i])
break;
}
}
passCount++;
}
if(passCount = reso)
break;
}
pthread_mutex_lock(&mutex); //get mutex lock
//Filling temporary arrays with current data
//===========================================
for(i = 0;i < cust;i++)
{
for(j = 0;j < reso;j++)
{
tempMaximum[i][j] = t->maximum[i][j];
tempAllocation[i][j] = t->allocation[i][j];
tempNeed[i][j] = t->need[i][j];
}
tempAvailable[i] = t->available[i];
tempRequest[i] = t->requestOrRelease[i];
}
//===========================================
//"Pretend" to allocate resources
for(i = 0;i < reso;i++)
{
tempAvailable[i] = tempAvailable[i] - tempRequest[i];
tempAllocation[custNum][i] = tempAllocation[custNum][i] + tempRequest[i];
tempNeed[custNum][i] = tempNeed[custNum][i] - tempRequest[i];
}
safeState = isSafeState(tempAvailable,tempNeed,tempAllocation);
if(safeState == 0)
{
for(i = 0;i < reso;i++)
{
t->available[i] = t->available[i] - tempRequest[i];
t->allocation[custNum][i] = t->allocation[custNum][i] + tempRequest[i];
t->need[custNum][i] = t->need[custNum][i] - tempRequest[i];
}
pthread_mutex_unlock(&mutex); //release mutex lock
end = true;
}
if(end == true)
break;
pthread_mutex_unlock(&mutex); //release mutex lock
}
printf("Request resources granted to consumer: %d",custNum);
}
void release_resources(struct threadData t)
{
int i;
pthread_mutex_lock(&mutex); //get mutex lock
for(i = 0;i < reso;i++)
{
t->available[i] = t->available[i] + t->requestOrRelease[i];
t->allocation[t->customer_num][i] = t->allocation[t->customer_num][i] - t->requestOrRelease[i];
}
pthread_mutex_unlock(&mutex); //release mutex lock
}
//Generates random integers for request and release vectors
void fillRequestRelease(int * array,int max0,int max1,int max2)
{
srand(time(NULL));
int r;
r = rand()%(max0+1);
array[0] = r;
r = rand()%(max1+1);
array[1] = r;
r = rand()%(max2+1);
array[2] = r;
}
As far as I can see, in your request_resources() function, t is not a pointer variable. So, instead of
t->requestOrRelease[0]
you should be using
t.requestOrRelease[0]
and so on.
t is not a pointer, so you must write t.field instead of t->field.
The important clue in the error message is "(have ‘struct threadData’)".
This means you are using the pointer dereference operator -> on a struct, instead of on a struct pointer. Use the member dereference operator . instead.

How to "combine" two int arrays?

Hello i have a little problem trying to "mix" two string arrays, i have searched about it but i have only found how to merge them or concatenate them, but thats not what i need.
i have two int arrays like this:
int no_items = 5;
int parent1[no_items], parent2[no_items];
if the arrays contains for example:
parent1[0] = 1;
parent1[1] = 2;
parent1[2] = 3;
parent1[3] = 4;
parent1[4] = 5;
and:
parent2[0] = 5;
parent2[1] = 1;
parent2[2] = 2;
parent2[3] = 3;
parent2[4] = 4;
given a "cross" point, for example 2:
parent1 should have his 2 first elements and the rest of parent2, and parent2 should have his first 2 elements and the rest of parent1. So the result should be:
parent1: 1,2 | 5,3,4
parent2: 5,1 | 2,3,4
where "|" is the break point index and the rest of elements should not be repeated.
How can i get this kind of mixing two int arrays? Thanks you!
at the moment i have this:
for(i = 0; i < cross_point; i++)
{
sprintf(buffer, "%d,", parent1[i]);
strcat(line1, buffer);
}
for(i = 0; i < cross_point; i++)
{
sprintf(buffer, "%d,", parent2[i]);
strcat(line2, buffer);
}
but i don´t know how to go further than the cross point.
int *find(int *begin, int *end, int value)
{
int *p = begin;
for ( ; p != end; ++p)
if (*p == value) break;
return p;
}
int i, j;
int output1[no_items] = {0};
int output2[no_items] = {0};
int crosspoint = 3;
memcpy(output1, parent1, crosspoint * sizeof(int));
for (i = crosspoint, j = 0; i < no_items; ++i)
{
while (find(output1, output1+i, parent2[j]) != output1+i) ++j;
output1[i] = parent2[j];
}
memcpy(output2, parent2, crosspoint * sizeof(int));
for (i = crosspoint, j = 0; i < no_items; ++i)
{
while (find(output2, output2+i, parent1[j]) != output2+i) ++j;
output2[i] = parent1[j];
}
memcpy(parent1, output1, sizeof(parent1));
memcpy(parent2, output2, sizeof(parent2));
Demo: http://ideone.com/xUt6nQ
something like this should do it if you aren't concerned about creating temporaries:
int no_items = 5;
int output1[no_items];
int output2[no_items];
for (int i = 0; i < no_items; i++){
if(i < crosspoint){
output1[i] = parent1[i];
output2[i] = parent2[i];
}else{
output1[i] = parent2[i];
output2[i] = parent1[i];
}
}
If you are concerned about temporaries you need to swap the values, the logic should be fairly similar to above.
int no_items = 5;
int temp = 0;
for (int i = 0; i < no_items; i++){
if(i < crosspoint){
/* don't need to do anything here */
}else{
temp = parent1[i];
parent1[i] = parent2[i];
parent2[i] = temp;
}
}

Resources