DISCLAIMER: This is not a homework question. I don't even go to school.
#include <stdio.h>
void printIntersect(float, float, float, float);
int main(){
int x, y, z, a;
float slopes[] = {5, 9, 4/3.0f, 2/3.0f, 3};
float inter[] = {3, 2, 1, 0, 5/3.0f};
for(x = 0; x < (sizeof(slopes) / sizeof(slopes[0])) - 1; x++)
for(y = 1; y < (sizeof(slopes) / sizeof(slopes[0])); y++)
for(z = 0; z < sizeof(inter) / sizeof(inter[0]); z++)
for(a = 0; a < sizeof(inter) / sizeof(inter[0]); a++)
if(slopes[x] != slopes[y])
printIntersect(slopes[x], slopes[y], inter[z], inter[a]);
return 0;
}
void printIntersect(float m_one, float m_two, float b_one, float b_two){
float m_final, b_final, x_intersect;
m_final = m_one - m_two;
b_final = b_two - b_one;
if(m_final < 0 && b_final < 0)
m_final *= -1.0f, b_final *= -1.0f;
if (b_final != 0)
x_intersect = b_final / m_final;
else
x_intersect = 0;
printf("The intersection of y = %.2fx %c %.2f and y = %.2fx %c %.2f is x = %.2f\n",
m_one, (b_one < 0) ? '-' : '+', b_one, m_two, (b_two < 0) ? '-' : '+', b_two, x_intersect);
return;
}
Scenario: There was an exercise in one of my C books that I'm unsure of. What I got out of the question was that I was to have two arrays: one representing the possible slopes of a line, the other representing all possible y intercepts. The goal was to use all possible combinations of slopes and intercepts with two lines to find their intersection. I was to ignore parallel lines and duplicate lines (which is implicitly ignored anyway considering if they can't be parallel, then there's no way that they can be the same line).
Assuming that's premise (and I really don't care at this point, it's just an exercise), the program I wrote uses 4 nested for loops. You can see why that concerns me, but then again, maybe the 4 of them are necessary.
Since I can't have parallel lines, I iterate the slopes by starting with that of the first line and then iterate through all other slopes in the array as the second line's slope. It's this way that I get all possible combinations of slopes.
Intercepts are different because I can have a lines of the same intercepts and still have them be different. So iteration between those doesn't need to account for duplicates. That being said, the way I iterate through the array of intercepts should account for every possible pair in those two lines.
If the lines are not parallel, I call a function which will print the x intercept.
My question is, could this O(n^4) solution been avoided or at least simplified? Do you have any tips on processing arrays like these?