Working out if an array of line segments intersect - c

I have been asked to store and draw an array of linesegments.
The program should print the message "No intersection" or "Found an intersection" (depending) before terminting if negative coordinates are entered or 2x MAXSEGMENTS segments have been entered.
int main(void) {
lineSeg_t line, allsegments[MAXSEGMENTS];
point_t a, b;
int pointssofar=0, i, v, w, x, y;
OpenGraphics();
while (pointssofar<=(2*MAXSEGMENTS)){
a=GetPoint();
x=XCoord(a);
y=YCoord(a);
if ((x<0)||(y<0))
break;
b=GetPoint();
v=XCoord(b);
w=YCoord(b);
if ((v<0)||(w<0))
break;
line=LineSeg(a, b);
DrawLineSeg(line);
allsegments[((pointssofar+2)/2)]=line;
for (i=0;i<(pointssofar/2);i++){
if (intersect(line, allsegments[i])==TRUE){
printf ("Found an intersection");
pointssofar=2*MAXSEGMENTS;
} else if (pointssofar==(2*MAXSEGMENTS)){
printf("No intersection");
}
}
}
for(i=0;i<(pointssofar/2);i++){
if (intersect(allsegments[pointssofar/2], allsegments[i])==FALSE){
printf("No intersection");
}
}
}
I'm having trouble outputting the messages. Think I'm stuck in the while loop and I'm really not sure how to get out!
Thank you in advance.

your while loop will never terminate, because there is no line in it that will ever make it's condition not true.
while (pointssofar<=(2*MAXSEGMENTS)){
the only time you change any of those values is that you get is
pointssofar=2*MAXSEGMENTS;
which satisfy the while loop condition.
you also have 2 break statements, but those are entirely dependant on the XCoord and YCoord functions. They might not ever actually be returning negative numbers.

You don't seem to increment pointssofar unless you find an intersection.

Related

C - segmentation fault when comparing integers

here is a part of my code. When I run my code, it's requesting an input from user and then matching it with another integer which recorded in my structure. When user input is matching, it is working correct. But when user enters a wrong input, it gives a segmentation fault. In where, I should make changes on my code?
long int userInput,endCheck; // Input from user
int flag=0; // check for match
int status;
int c; // controlling ctrl+D
int position= 999; // position of where the user input and data matched
LABEL:
printf("\n\t---------------------------------------\n");
printf("\n\nPlease enter the student ID which you want to find(3-times CTRL+D for finish):\n");
scanf("%d",&userInput);
if( (c=getchar()) == EOF){
exit(0);
}
for(i=0;i<lines,flag==0;i++){
if(index[i].id == userInput){
position=i;
flag=1;
}else{
position=999;
}
}
if(flag==0){
printf("id not found");
}
studentInfo info; // for storing the information which we will take between determined offsets
if(position!= 999){
if ( (pos = lseek(mainFile,index[position].offset , SEEK_SET)) == -1)/*going to determined offset and setting it as starting offset*/
{ perror("classlist"); return 4; }
while ( (ret= read(mainFile,&info, sizeof(info))) > 0 ){
printf("\n\nStudent ID: %d, Student Name: %s\n\n",info.id,info.name);
break;// to not take another students' informations.
}
}
flag=0;
goto LABEL;
printf("Program is terminated");
The right way to do that loop with the unwanted comma is like this. When you find the right index[i].id you can exit the loop early by using break.
for(i=0;i<lines;i++){
if(index[i].id == userInput){
position=i;
flag=1;
break;
}
}
You don't need the else branch as position is set to 999 from the outset of the code. But really you shouldn't use position in this fashion. What if you have more than 999 records? You're already using flag to identify if you've set position to a valid value. You should replace any instance of if(position!= 999) with if(flag).
Or since position is a signed int, you could use a negative value and ditch the flag.
The reason can be the fact that you are reaching an index that doesn't exist in the end of cycle, in the moment of the "if" statement with iterator "i".
Or in the last if, where you access a "position" index of the array. Check those limits.
Also, try GDB, is useful for solving this kind of problems.

Frequency of each word of text file. Error while allocating memory?

Good evening everyone!
I have started messing around with strings and pointers in C.
I want to write a programm that reads a text file, then calculating the frequency of each word and printing it.
My variables are:
FILE *fp;
char *words[N] //N defined 100
int i=0, y=0;
int *freq;
int freq_count=0;;
int word_number=0;
The code part:
for(i=0;i<word_counter;i++){
while(y<word_counter){
if(strcmp(words[i],words[y]==0){
freq1++;
} y++;
}
if(i==0){
freq=(int*)malloc(sizeof(int));
strcpy(freq, freq1); freq1=0;
}
else{
freq=(int*)realloc(freq, (i+1)*sizeof(int));
strcpy(freq, freq1); freq1=0;
}
y=0;
}
I get several errors running this...What is wrong?
Take into consideration that in words[N] i have put each word of the text by itself in each cell.
Thank you all in advance.
Maybe another array is not what you want, but still better than using realloc and condition in loop.
int freq[N];
for(i=0;i<word_counter;i++){
freq1 = 0;
for(y=0;y<word_counter;y++){
if(strcmp(words[i],words[y]==0)
freq1++;
}
freq[i] = freq1;
}

Binary Search in C using recursion

The program crashes in finding a number which is not available in the array.The code works perfectly when i search for elements which are available in the array.Help much appreciated.
#include<stdio.h>
int binarySearch(int a[],int s,int key)
{
int middle;
if(s!=1)
middle=s/2;
if(a[middle]==key)
return 1;
else if(key<a[middle])
binarySearch(a,middle,key);
else if(key>a[middle])
binarySearch(&a[middle],middle,key);
else
return 0;
}
void main()
{
int i;
int a[]={1,2,3,4,6,9,10,11};
for (i =0;i<8;i++)
printf("%i ",a[i]);
if(binarySearch(a,8,5))
printf("\nFound");
else
printf("\nNot Found");
}
Change
if(s!=1)
middle=s/2;
if(a[middle]==key)
return 1;
else if(key<a[middle])binarySearch(a,middle,key);
else if(key>a[middle])binarySearch(&a[middle],middle,key);
to
if (s != 1){
middle = s / 2;
if (a[middle] == key)
return 1;
else if (key<a[middle])binarySearch(a, middle, key);
else if (key>a[middle])binarySearch(&a[middle], middle, key);
}
The variable middle is initialized only if s!=1.
I have run this code and got the value Not Found for input 5.
If you are running your code in release mode, try building it in debug mode and run step by step you will see what happens when middle is used directly without assigning it a specific value. This is harmful.
Hope this helps.
The code if(key<a[middle])binarySearch(a,middle,key); does not return anything.
Try if(key<a[middle]) return binarySearch(a,middle,key);
This may still not work as you intend it to, but at least you will get past the major, immediately visible, cause of runaway recursion.
Because there is no case if the s == 1. "Middle" is not initialized and a[middle] is potential crash, or it will just go infinite.
A few notes:
Every branch of a recursive function should return something. You'll need to modify your recursive calls to return the call
Change
binarySearch(a, middle, key)
to
return binarySearch(a, middle, key)
Also, make sure middle is computed properly. You don't properly initialize it in the situation where s == 1. You'll want this to start at 0 most likely.

Variable value changes for no apparent reason

In my code I define a step size "h" before a while loop. Somehow it seems to change by itself when I try to use it in the loop. If I define it inside the loop it seems to be ok, but the data I get doesn't seem to be right so I'm guessing the problem might be related.
Even when I print it at this location (see the printf in the code) the output is 3 values and I have no idea why. If you see anything else that's not related but seems wrong please tell me, as I said I'm getting unexpected values (it may just be my formulas).
int main()
{
FILE *f1;
f1 = fopen("Question2 part 3 solution.txt", "w");
double r0=0.05;
double dr0=-a*a*r0/sqrt(1+pow(a*a*r0,2)),h=0.01;
double k[4][3],x[]={dr0,z0,T0,r0},x1[]={0,0,0,0}, s=0;
int i,j;
while(s<=1)
{
//Runge-Kutta
for (j=0;j<4;j++)
{
for (i=0;i<4;i++)
{
if (j==0){k[i][0]=h*System(i,x[0],x[1],x[2],x[3]);}
if (j==1){k[i][1]=h*System(i,x[0]+k[0][0]/2.0,x[1]+k[1][0]/2.0,x[2]+k[2][0]/2.0,x[3]+k[3][0]/2.0);}
if (j==2){k[i][2]=h*System(i,x[0]+k[0][1]/2.0,x[1]+k[1][1]/2.0,x[2]+k[2][1]/2.0,x[3]+k[3][1]/2.0);}
if (j==3){k[i][3]=h*System(i,x[0]+k[0][2],x[1]+k[1][2],x[2]+k[2][2],x[3]+k[3][2]);}
}
}
for (i=0;i<4;i++)
{
x[i]=x[i]+(k[i][0]+2.0*k[i][1]+2.0*k[i][2]+k[i][3])/6.0;
}
printf("%8.3lf",h);
s+=h;
}
fclose(f1);
return(0);
}
double System(int i,double dr, double z, double T, double r)
{
//printf("%e\t%e\t%e\t%e\n",dr,z,T,r);
if (T==T0 && z==z0 && i==0) {return (-a*a*dr)*pow(1-dr*dr,3/2)/2.0;}
if (i==0 && T!=0){return (-a*a*r*(1-dr*dr)-dr*sqrt(1-dr*dr))/T;}
if (i==1){return (-sqrt(1-dr*dr));}
if (i==2){return (-a*a*r*dr+sqrt(1-dr*dr));}
if (i==3){return (dr);}
//if (i==3){return (-m2*l1*l2*B*theta1dt*theta2dt*sin(theta2-theta1)-l2*m2*g*B*sin(theta2));}
}
Thanks in advance!
See the declaration of k:
double k[4][3]
And then see this statement
k[i][3]=...
Here you write beyond the boundaries of the array, leading to undefined behavior.
You are overrunning the memory, variable k is defined as double k[4][3], but you are updating k[i][3]when j==3

Deciding the base condition in backtracking recursive algorithm

I was solving the N Queen problem where we need to place 4 queens on a 4 X 4 chess board such that no two queens can attack each other. I tried this earlier but my approach did not involve backtracking, so I was trying again. The code snippets are
int size=4,i,j;
int arr[4][4];
int lastjindex[4]; // to store the last location which we may need to backtrack
void placeQueen(int i,int j)
{
int availableornot=0;
for(j=0;j<size;j++)
{
if(isAvailable(i,j)==1)
{
availableornot=1;
break;
}
}
if(availableornot==1)
{
arr[i][j]=1;
lastjindex[i]=j;
if((i+1)!=size)
{
placeQueen(i+1,0);
}
}
else
{
// no column was availabe so we backtrack
arr[i-1][lastjindex[i-1]]=0;
placeQueen(i-1,lastjindex[i-1]+1);
}
}
The isAvailable() method returns 1 if arr[i][j] is not under attack, else it returns 0.
int isAvailable(int i,int j)
{
int m,n,flag=0;
for(m=0;m<i;m++)
{
for(n=0;n<size;n++)
{
int k=abs(i-m);
int l=abs(j-n);
if(arr[m][j]==0 || arr[k][l]==0)
{
flag=1;
break;
// means that spot is available
}
}
}
return flag;
}
I call the above method from main as
placeQueen(0,0);
My program compiles successfully but it prints all zeroes.
Is there any problem with my recursion? Please help me correct my code as I am trying to learn how to implement backtracking algorithms!
Also I am not able to decide the base condition to end recursion. How do I choose it here?
There's no printing in the code you posted. If you print after you have backtracked, you will be back to the initial condition of no queens on the board. Print after you have placed N queens, which is also the end condition for recursion. If you only want to print one solution, exit after printing, or set a flag that tells the caller that you're done so you pop all the way out. If you print all solutions, that will include reflections and rotations. You can eliminate one axis of reflection by only placing queens within size/2 in the first level.
Also, there are some clear logic errors in you code, such as
arr[m][j]==0 || arr[k][l]==0
A queen can only be placed if it isn't attacked on the file and it isn't attacked along a diagonal. Use a debugger or add printfs to your code to trace where it is trying to place queens -- that will help you figure out what it is doing wrong.
And aside from being wrong, your isAvailable is very inefficient. You want to know if the [i,j] square is attacked along the file or a diagonal. For that you should have a single loop over the rows of the previous queens for (m = 0; m < i; m++), but you only need three tests, not a loop, to check the file and the diagonals. As soon as you find any previous queen on a file or diagonal, you're done, and the square isn't available -- return false. (And ignore people who tell you that a function should only have one return -- they are wrong, and there are lengthly discussions here at SO and even scientific studies of error rates in code that bear this out.) Only if no previous queen is found is the square available.
Your placeQueen is also wrong. For each available square on a row, you need to place a queen and then recurse, but you're just finding the first available square. And backtracking is achieved simply by removing the queen you placed and then returning ... the previous level of placeQueen will try the next available spot.
Again, trace the code to see what it's doing. And, even more importantly, think through the logic of what is needed. Write your algorithm in words, convince yourself that it will solve the problem, then write the code to carry out the algorithm.
#include <stdio.h>
#define SIZE 4
int size=SIZE;
int arr[SIZE][SIZE] = { 0 };
void placeQueen(int col){
int r,c;
if(col == size){//all queen put!
//print out
for(r = 0;r<size;++r){
for(c = 0;c<size;++c)
printf("%d", arr[c][r]);
printf("\n");
}
printf("\n");
return ;
}
for(r=0;r<size;++r){
if(isAvailable(col, r)==1){
arr[col][r]=1;
placeQueen(col+1);
arr[col][r]=0;//reset
}
}
}
int isAvailable(int col,int row){
int c;
for(c=0;c<col;++c){
int d = col - c;
if(arr[c][row]==1)
return 0;//queen already same row
if(row+d < size && arr[c][row+d]==1 || row-d >= 0 && arr[c][row-d]==1)
return 0;//queen already same slanting position
}
return 1;
}
int main(){
placeQueen(0);
return 0;
}

Resources