Mar 15, 2022

Check if 2 line segments intersect and find point of intersection

 #include <iostream>

using namespace std;


// Given two straight line segments (represented as a start point and an end point),

// compute the point of intersection, if any.


//Logic - To be able to intersect the slopes should be opposite

bool doIntersect(int sx, int sy, int ex, int ey, int s1x, int s1y, int e1x, int e1y)

{

    float slope1 = (sy-s1y)/(sx-s1x);

    float slope2 = (e1y-sy)/(e1x-sx);

    float slope3 = (ey-s1y)/(ex-s1x);

    float slope4 = (e1y-ey)/(e1x-ex);

    

    if(slope1>=slope2 && slope3>=slope4)

        return false;

    if(slope1>=slope2 && slope3<=slope4)

        return true;

    if(slope1<=slope2 && slope3<=slope4)

        return false;

    if(slope1<=slope2 && slope3>=slope4)

        return true;


    

}


//point of intersect can be computed using slope formula

//say Ix. Iy is the intersection then slope(S,I) = slope(I,E) and slope(S1,I) = slope(I,E1)

//This will generate 2 equations with 2 unknowns and hence can be solved.

//special cases should be checked where either segments start or end lie on the other. In that case

// the distance formula can be used to verify.


int main() {

// your code goes here

bool res = doIntersect(1,2,3,4,2,6,2,-8);

if(res)

    cout << "intersect";

else

    cout << "don't intersect";

return 0;

}


Mar 12, 2022

Grid travel (find path by dynamic prog)

 #include <iostream>

#include <cstring>

using namespace std;

// Imagine a robot sitting on the upper left corner of grid with r rows and c columns.

// The robot can only move in two directions, right and down, but certain cells are "off limits" such that

// the robot cannot step on them. Design an algorithm to find a path for the robot from the top left to

// the bottom right.


bool findPath(int r, int c, int currow, int curcol, int path[], int top)

{

    

    if(r<0 || c<0)

        return false;

        

    if(r ==1 && c == 1)

    {

        return true;

    }

    

    if(r == currow+1 && c == curcol+1)

        return true;

    

    if(currow+1 > r)

        return false;

        

    if(curcol+1 > c)

        return false;

        


    if(curcol ==0 && currow == 2)   // 1=off-limit cell, 0=ok

        return false;

    

    if(curcol ==1 && currow == 4)   // 1=off-limit cell, 0=ok

        return false;

        

    path[top] = 0; //down   

    bool b1 = findPath(r, c, currow+1, curcol, path, top+1);

    

    if(b1) return b1;

    

    path[top] = 1; //right

    bool b2 = findPath(r, c, currow, curcol+1, path, top+1);

    

    if(b2) return b2;

    

    return false;

}


void printPath(int a[])

{

    for(int i=0; i<50 && a[i]!=-1; i++)

        cout << ((a[i] == 0) ? 'd':'r')  << "-->";

}


int main() {

// your code goes here

int path[50];

memset(path, -1, 50*sizeof(int));

findPath(5, 5, 0, 0, path, 0);

printPath(path);

return 0;

}


output:
d-->r-->d-->d-->r-->d-->r-->r-->