Okay so I have a problem that involves assigning random masses to cars and assigning these into random positions (on a "grid" if you would like to picture it that way) which will eventually move around and cars with a bigger mass will destroy the smaller ones and then I must de-allocate the memory . I shrunk this grid down to a 5 by 5 grid with 5 cars just to see if I could grasp the problem, but after many hours of trying I cannot figure out linked lists...
My problem is assigning these cars to random places and making sure none are in the same spot to begin with.
Here is the section of code I have tried to start (including the part where I built the linked list):
//--first car--
printf("weight %d, xpos %d, ypos %d\n",carsptr->weight,carsptr->xdim,carsptr->ydim);
//--build the linked list--
for (i=0; i<ncars-1; i++)
{
carsptr->nextptr=malloc(sizeof(struct cars));
carsptr=carsptr->nextptr;
carsptr->weight=rand()%(50)+1;
carsptr->xdim=rand()%(dim1);
carsptr->ydim=rand()%(dim2);
printf("weight %d, xpos %d, ypos %d\n",carsptr->weight,carsptr->xdim,carsptr->ydim);
}
carsptr->nextptr=NULL;
//--move a car if it is in the same spot as another--
i=0;
for (i=0; i<ncars; i++)
{
carsptr=&a; //start the linked list from the beginning
carstpr=carsptr->nextptr
if (carsptr->xdim==carsptr->nextptr->carsptr->xdim)
{
carsptr->nextptr->xdim=rand()%(dim1);
}
}
I know I need to loop through my list and when I come across a value that has the same xdim (x-dimension) then I need to loop through the ydim (y-dimension) to check and see if that is the same.
This is my entire code block if needed:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
//--array and car definitions--
#define dim1 5
#define dim2 5
#define ncars 10
#define numit 10
//--structure--
struct cars{
int xdim;
int ydim;
int weight;
struct cars *nextptr;
};
int main()
{
//--initialize the variables--
int i=0;
int j=0;
int k=0;
int N=50;
int Nbox=100;
int temp=0;
int X=0;
int choice=4;
struct cars a={rand()%(dim1),rand()%(dim2),rand()%(50)+1,NULL};
struct cars *carsptr=&a;
//--first car--
printf("weight %d, xpos %d, ypos %d\n",carsptr->weight,carsptr->xdim,carsptr->ydim);
//--build the linked list--
for (i=0; i<ncars-1; i++)
{
carsptr->nextptr=malloc(sizeof(struct cars));
carsptr=carsptr->nextptr;
carsptr->weight=rand()%(50)+1;
carsptr->xdim=rand()%(dim1);
carsptr->ydim=rand()%(dim2);
printf("weight %d, xpos %d, ypos %d\n",carsptr->weight,carsptr->xdim,carsptr->ydim);
}
carsptr->nextptr=NULL;
//--move a car if it is in the same spot as another--
i=0;
for (i=0; i<ncars; i++)
{
carsptr=&a; //start the linked list from the beginning
carstpr=carsptr->nextptr
if (carsptr->xdim==carsptr->nextptr->carsptr->xdim)
{
carsptr->nextptr->xdim=rand()%(dim1);
}
}
return(0);
}
Any help would be greatly appreciated!