Find if a line segment is a sub segment of another line - c

How do I find if a certain line is a sub segment of another line?
Line 1: (2,2) and (20,20)
Line 2: (5,5) and (15,15)
I know how to do this mathematically but having a hard time coding it in c. I found out that the slopes are equal but cant find a way to check that the lines are part of the same line and not just parallel.

This seems to be homework, so I will only sketch an answer. You will have to code it yourself.
First, are the slopes the same? If not, they only have one point in common; stop. Assuming the coordinates are integers, you can avoid floating-point errors by computing each dx and dy, and cross-multiplying (h/t to Weather Vane’s comment above).
Second, do the extended lines have a point in common? Can do this by finding y-intercepts or various other ways. If not, they’re parallel; stop.
Having reached this point, we know the segments are on the same line, so now we have to test the intervals. If they’re horizontal, look at x; if vertical, look at y; if slanted, pick one coordinate, either one will work.
Sort each pair of endpoints to get a and b such that a < b. Then, simply compare the leftmost endpoints of each segment, and the rightmost. Remember that either or both might be equal.

Related

constructing a non deterministic turing machine

Draw the diagram of a two tape Non deterministic Turing Machine M that decides the language
L={w∈Σ* | w=uuu ∈Σ* }
if i could get help explaining the steps how to construct the NDTM (linguistically), I believe I could draw the diagram but I couldnt come out with an answer..
thank you
By u*u*u (viewed in the edit history), I presume what you intend is the language of all words of the form u^3 (u repeated three times) where u is any string over the alphabet.
Our NDTM needs to accept strings in the language in at least one way, and it must never accept anything not in the language. In particular, the key is that an NDTM can reject strings in the language, as long as some path through the NDTM does accept every string in the language.
Given that, our first step can be do guess about the length of u. The NDTM can mark three tape symbols (say, by writing versions of the symbols that are underlined) by nondeterministically transitioning from state q0 to q1 then q2 at arbitrary points while scanning right. Then, we can reset the tape head and use a deterministic TM to answer the question: did the split we guessed in the first step result in a string of the form u^3?
This is deterministic since we know the delineation of parts. We can check the first two parts (say, by bouncing back ad forth and marking symbols we've already processed), and then the second two parts (using the same technique, but applied to the 2nd and 3rd parts).
We have reduced the problem to that of checking whether a string is of the form w|w where we know the split. This deterministic TM is easier to come up with. When we put it after the NDTM that guesses about how to split up the initial input, we get a NDTM that can (and for exactly one guess, does) accept any string of the form u^3, but cannot possibly accept anything else. This is what we were after and we are done.

Problems to solve using control instructions in C for practice

Need some good problems which students can think of and apply their own logic to solve them using control instructions only. The topics covered until now are basic, not even arrays are done yet. But, I want students to be perfect before proceeding to higher topics.
I tried searching for some example problems, none were as I expected / they were the ones which I already knew.
Some of which I know:
Write a program to find out the value of a^b without using built in functions.
Write a program to find out Armstrong numbers between a range.
Write a program to print binary equivalent of a number in reverse order (since arrays are not yet done, just simple logic to print the remainder and divide the number further)
Count all -ve, +ve and 0 numbers entered by user until user wishes to terminate the program.
Write a program to display all divisors of a given number.
Write a program to find if the given number is prime or not.
Check if the given number is odd or even.
Need more good logically interesting problems which would help students to build their problem solving capability.
Thanks.
PS: Please forgive me if this question is vague or not to the point coz this question has scope for vast answers and I cannot accept a single answer, I guess?
Check if number is a palindrome (1234554321)
Rewrite a function using write() to print a number in the console (similar to printf("%d", ...))
A function that writes all combinations of 2 digits starting from 12 to 89, not allowing twice the same digit, nor a different order (12, 13, ..., 19, 23, 24... : skipping 21 because it's done with 12)
A function that write all combinations of n digits (n given as a parameter from 1 to 9) with the same rules (without using arrays)
Print first 33 terms of Fibonacci-Series
Write factorial of n being input from keyboard on console.
Find hours,minutes,seconds from given seconds.(305 s = 5m + 5s ....)
Calculate dot-product and cross-product of two 2D vectors.
Find the intersecting point of two lines(m=slope, (x0,y0)=a point for each line)
Calculate sin(pi/4) with using series expansion
Print the minimum of values given from keyboard on screen.
Simulate **and** , **or** and **xor** gates.
Find projection of a vector(3D) on another vector.
Find area of a polygon(2D)
Calculate the integral of x-square between x=0 and x=3 using integration by trapezoidal rule
Find roots of: (x-square) plus (two times x) plus (one) equals (zero)

C programming language, shortest path

I'm am writing a code to find the shortest distance between two points. My code is working perfect till now. I mean it finds the distance and the path that they should pass. I need to print this information, but I should make a print function. The way it works is something like that: For example initial point is 4 and final is 13.
I should come up with an algorithm that check their intermediate points. Let's say between 4 & 13 there is point : 7
4--7--13 Now I need to check every point between them like:
4--6--7--9--13 To be more specific it will check if there is a point between 4-6 and 6-7 and 7-9 and 9-13. So next in the next iteration it may be formed another list like:
4--2--6--7--5--9--17--13 Now let's say that there will not be any intermediate value between them. And that is what I should print. I really would appreciate any help, suggestion that you may give to me
The Warshall-Floyd algorithm (used by the OP), has a version which is able to determine the path in addition to the distance between nodes of a graph:
Floyd-Warshall algorithm with path-reconstruction
However, it must be noted that this is not the best possible algorithm to solve the shortest-path problem.
This sounds like recursion would be the best way to do this. If it already can find the shortest path, im assuming you have a function written to find the shortest path between 2 points. Maybe you could recursively break down the list, find the shortest path and append that point to a list.
Edit, sorry i misread your question, you need to find the midpoint. Pass a recursive function the whole list of points and find a midpoint. If one exists, add it to a list. If there is no midpoint dont append anything. Continue calling this function until you come to the base case, which should be 1 or 2 points in the list

storing strings in an array in a compact way [duplicate]

I bet somebody has solved this before, but my searches have come up empty.
I want to pack a list of words into a buffer, keeping track of the starting position and length of each word. The trick is that I'd like to pack the buffer efficiently by eliminating the redundancy.
Example: doll dollhouse house
These can be packed into the buffer simply as dollhouse, remembering that doll is four letters starting at position 0, dollhouse is nine letters at 0, and house is five letters at 3.
What I've come up with so far is:
Sort the words longest to shortest: (dollhouse, house, doll)
Scan the buffer to see if the string already exists as a substring, if so note the location.
If it doesn't already exist, add it to the end of the buffer.
Since long words often contain shorter words, this works pretty well, but it should be possible to do significantly better. For example, if I extend the word list to include ragdoll, then my algorithm comes up with dollhouseragdoll which is less efficient than ragdollhouse.
This is a preprocessing step, so I'm not terribly worried about speed. O(n^2) is fine. On the other hand, my actual list has tens of thousands of words, so O(n!) is probably out of the question.
As a side note, this storage scheme is used for the data in the `name' table of a TrueType font, cf. http://www.microsoft.com/typography/otspec/name.htm
This is the shortest superstring problem: find the shortest string that contains a set of given strings as substrings. According to this IEEE paper (which you may not have access to unfortunately), solving this problem exactly is NP-complete. However, heuristic solutions are available.
As a first step, you should find all strings that are substrings of other strings and delete them (of course you still need to record their positions relative to the containing strings somehow). These fully-contained strings can be found efficiently using a generalised suffix tree.
Then, by repeatedly merging the two strings having longest overlap, you are guaranteed to produce a solution whose length is not worse than 4 times the minimum possible length. It should be possible to find overlap sizes quickly by using two radix trees as suggested by a comment by Zifre on Konrad Rudolph's answer. Or, you might be able to use the generalised suffix tree somehow.
I'm sorry I can't dig up a decent link for you -- there doesn't seem to be a Wikipedia page, or any publicly accessible information on this particular problem. It is briefly mentioned here, though no suggested solutions are provided.
I think you can use a Radix Tree. It costs some memory because of pointers to leafs and parents, but it is easy to match up strings (O(k) (where k is the longest string size).
My first thought here is: use a data structure to determine common prefixes and suffixes of your strings. Then sort the words under consideration of these prefixes and postfixes. This would result in your desired ragdollhouse.
Looks similar to the Knapsack problem, which is NP-complete, so there is not a "definitive" algorithm.
I did a lab back in college where we tasked with implementing a simple compression program.
What we did was sequentially apply these techniques to text:
BWT (Burrows-Wheeler transform): helps reorder letters into sequences of identical letters (hint* there are mathematical substitutions for getting the letters instead of actually doing the rotations)
MTF (Move to front transform): Rewrites the sequence of letters as a sequence of indices of a dynamic list.
Huffman encoding: A form of entropy encoding that constructs a variable-length code table in which shorter codes are given to frequently encountered symbols and longer codes are given to infrequently encountered symbols
Here, I found the assignment page.
To get back your original text, you do (1) Huffman decoding, (2) inverse MTF, and then (3) inverse BWT. There are several good resources on all of this on the Interwebs.
Refine step 3.
Look through current list and see whether any word in the list starts with a suffix of the current word. (You might want to keep the suffix longer than some length - longer than 1, for example).
If yes, then add the distinct prefix to this word as a prefix to the existing word, and adjust all existing references appropriately (slow!)
If no, add word to end of list as in current step 3.
This would give you 'ragdollhouse' as the stored data in your example. It is not clear whether it would always work optimally (if you also had 'barbiedoll' and 'dollar' in the word list, for example).
I would not reinvent this wheel yet another time. There has already gone an enormous amount of manpower into compression algorithms, why not take one of the already available ones?
Here are a few good choices:
gzip for fast compression / decompression speed
bzip2 for a bit bitter compression but much slower decompression
LZMA for very high compression ratio and fast decompression (faster than bzip2 but slower than gzip)
lzop for very fast compression / decompression
If you use Java, gzip is already integrated.
It's not clear what do you want to do.
Do you want a data structure that lets to you store in a memory-conscious manner the strings while letting operations like search possible in a reasonable amount of time?
Do you just want an array of words, compressed?
In the first case, you can go for a patricia trie or a String B-Tree.
For the second case, you can just adopt some index compression techinique, like that:
If you have something like:
aaa
aaab
aasd
abaco
abad
You can compress like that:
0aaa
3b
2sd
1baco
2ad
The number is the length of the largest common prefix with the preceding string.
You can tweak that schema, for ex. planning a "restart" of the common prefix after just K words, for a fast reconstruction

To find all possible permutations of a given string

This is just to work out a problem which looks pretty interesting. I tried to think over it, but couldn't find the way to solve this, in efficient time. May be my concepts are still building up... anyways the question is as follows..
Wanted to find out all possible permutation of a given string....... Also, share if there could be any possible variations to this problem.
I found out a solution on net, that uses recursion.. but that doesn't satisfies as it looks bit erroneous.
the program is as follows:-
void permute(char s[], int d)
{
int i;
if(d == strlen(s))
printf("%s",s);
else
{
for(i=d;i<strlen(s);i++)
{
swap(s[d],s[i]);
permute(s,d+1);
swap(s[d],s[i]);
}
}
}
If this program looks good (it is giving error when i ran it), then please provide a small example to understand this, as i am still developing recursion concepts..
Any other efficient algorithm, if exists, can also be discussed....
And Please,, this is not a HW........
Thanks.............
The code looks correct, though you only have the core of the algorithm, not a complete program. You'll have to provide the missing bits: headers, a main function, and a swap macro (you could make swap a function by calling it as swap(s, d, i)).
To understand the algorithm, it would be instructive to add some tracing output, say printf("permute(%s, %d)", s, d) at the beginning of the permute function, and run the program with a 3- or 4-character string.
The basic principle is that each recursive call to permute successively places each remaining element at position d; the element that was at position d is saved by putting it where the aforementioned remaining element was (i.e. the elements are swapped). For each placement, permute is called recursively to generate all desired substrings after the position d. So the top-level call (d=0) to permute successively tries all elements in position 0, second-level calls (d=1) try all elements in position 1 except for the one that's already in position 0, etc. The next-to-deepest calls (d=n-1) have a single element to try in the last position, and the deepest calls (d=n) print the resulting permutation.
The core algorithm requires Θ(n·n!) running time, which is the best possible since that's the size of the output. However this implementation is less efficient that it could be because it recomputes strlen(s) at every iteration, for a Θ(n²·n!) running time; the simple fix of precomputing the length would yield Θ(n·n!). The implementation requires Θ(n) memory, which is the best possible since that's the size of the input.
For an explanation of the recursion see Gilles answer.
Your code has some problems. First it will be hard to implement the required swap as a function in C, since C lacks the concept of call by reference. You could try to do this with a macro, but then you'd either have to use the exclusive-or trick to swap values in place, or use a temporary variable.
Then your repeated use of strlen on every recursion level blows up your complexity of the program. As you give it this is done at every iteration of every recursion level. Since your string even changes (because of the swaps) the compiler wouldn't even be able to notice that this is always the same. So he wouldn't be able to optimize anything. Searching for the terminating '\0' in your string would dominate all other instructions by far if you implement it like that.

Resources