DISCLAIMER: This is not a matter of homework. 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: One of my C books had an exercise that I’m not sure about. I realized that I should have two arrays: one of the possible slopes of the line, the other - all possible intercepts. The goal was to use all possible combinations of slopes and intercepts with two lines to find their intersection. I had to ignore parallel lines and duplicate lines (which are implicitly ignored anyway, if they cannot be parallel, then there is no way that they could be the same line).
Assuming the premise (and I really don't care, it's just an exercise), the program I wrote uses 4 nested loops. You can understand why this concerns me, but again, maybe 4 of them are necessary.
Since I cannot have parallel lines, I repeat the slopes starting from the first line, and then iterate over all the other slopes of the array as the second slope of the line. Thus, I get all possible combinations of slopes.
Interceptions are different, because I can have lines with the same interceptions, and they will still be different. Thus, the iteration between them does not require duplicates. At the same time, as I repeat the array of interceptions, every possible pair in these two lines should be taken into account.
If the lines are not parallel, I call a function that will print an intercept x.
My question is, can this be avoided, or at least simplified this solution to O (n ^ 4)? Do you have any tips on handling such arrays?