SlideShare a Scribd company logo
1 of 6
Download to read offline
Need help with this sorting problem.
The code I have so far feels about 70% complete. (I plan to get rid of the qsort function and
implement my own merge-sort algo but for now, you can use it.) There are a few errors that
prevent it from running. Here is the code I have so far:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define MAX_N 500000
#define MAX_S 10
struct tugboat {
int x, y, dist;
char name[21];
};
int cmp(const void* a, const void* b) {
const struct tugboat* t1 = (const struct tugboat*) a;
const struct tugboat* t2 = (const struct tugboat*) b;
if (t1->dist != t2->dist) {
return t1->dist - t2->dist;
} else {
return strcmp(t1->name, t2->name);
}
}
int main() {
int xs, ys, xn, yn;
scanf("%d%d%d%d", &xs, &ys, &xn, &yn);
int n;
scanf("%d", &n);
struct tugboat tugboats[MAX_N];
int i;
for (i = 0; i < n; i++) {
scanf("%d%d%s", &tugboats[i].x, &tugboats[i].y, tugboats[i].name);
int dx = tugboats[i].x - xs;
int dy = tugboats[i].y - ys;
tugboats[i].dist = dx * dx + dy * dy;
}
qsort(tugboats, n, sizeof(struct tugboat), cmp);
int num_tugs = 0;
char tugs[MAX_N][21];
int prev_x = xs, prev_y = ys;
for (i = 0; i < n; i++) {
if (tugboats[i].x >= prev_x && tugboats[i].y >= prev_y) {
num_tugs++;
strcpy(tugs[num_tugs - 1], tugboats[i].name);
prev_x = tugboats[i].x;
prev_y = tugboats[i].y;
}
}
printf("%dn", num_tugs);
for (i = 0; i < num_tugs; i++) {
printf("%sn", tugs[i]);
}
return 0;
}
Here are the instructions:
Tugboat Troubles Objective Give practice with sorting in C. Story The ship's engine has ceased,
and now begins the preparations of taking the ship to the harbor for repairs. Luckily it's a straight
shot to the harbor. The bad news is that the journey is long. There are several tugboats currently
scattered throughout the ocean that can help move the ship to the harbor, but they may have to go
out of their way to assist, and taking your crippled ship the full distance is going to be taxing on
resources for any 1 particular tugboat. The tugboats have made an agreement. The tugboats will
take the shortest path to the direct route that your ship will travel. Once the tugboats are on the
route the closest tugboat to your ship will travel from its starting location on your ship's route to
your ship's current location. Then the tugboat will tow your ship back to where the tugboat
started on your ship's route. When your ship reaches that tugboat's starting location, the tugboat
will stop towing your ship and will move back to its original location. After which the process
will repeat with the next closest tugboat. If multiple tugboats would arrive at the same location
on the ship's route, then only the tugboat that is closest to the location on the ship's route would
move to that location. If multiple tugboats are the same distance from the location on the ship's
route, then the tugboat with the lexicographically earliest name would move to the route. It is
dangerous on the high seas, and you're afraid that your ship may fall victim to pirates that are
pretending to be a valid tugboat. Your goal is to produce the names of the tugboats that will tow
your ship to the harbor in the order they tow so that your ship. Problem Given the current
location of your broken ship, the location of the harbor, and a list of tugboats with both their
location and name, determine the number and order in which the tugboats will tow your ship
based on the behavior specified above. Input Input will begin with a line containing 4 integers, x
s , y s , x h , and y h ( 1 0 6 x s , y s , x h , y h 1 0 6 ) , representing the x and y coordinates of
your ship and the x and y coordinates of the harbor respectively. The following line will contain
a single integer, n ( 1 n 500 , 000 ) , representing the number of tugboats. The following n lines
will each contain a tugboat description (one per line). The tugboat description will contain 2
integers, x and y ( 1 0 6 x , y 1 0 6 ) , representing the x and y coordinates of the tugboat
respectively, followed by a string, s , representing the name of the tugboat. The name will
contain only upper and lower case characters of which there will be at most 20 . There will be at
least 1 tugboat at the location of the harbor. Your ship does not start at the harbor. Output Output
should begin with a number k , representing the number of tugboats that will tow your broken
ship. Following this should be k lines each containing a single name of a tugboat, the full list
comprise the list of the tugboats that will tow your ship in the order they tow your ship.
Explanation Case 1 The broken ship begins at location ( 0 , 0 ) . The ship is going to the harbor
located at location ( 12 , 8 ) The next line states that there are 4 tugboats in the ocean. The
tugboats are at locations ( 10 , 2 ) , ( 0 , 13 ) , ( 12 , 8 ) , and ( 7 , 9 ) . The names of the boats
were ShipOnTheWater, KnotGonnaHelp, SailingPeacefully, and ADerelictBoatTower. If the
ship were to move onto the line that passes between the points ( 0 , 0 ) and ( 12 , 8 ) , then - The
first tugboat (ShipOnTheWater) would end up at point ( 6 , 4 ) - The second tugboat
(KnotGonnaHelp) would end up at point ( 6 , 4 ) - The third tugboat (SailingPeacefully) would
end up at point ( 12 , 8 ) - The fourth tugboat (ADerelictBoat Tower) would end up at point ( 9 ,
6 ) The first and second tugboat have their location coincide. Only 1 will tow the ship. The first
tugboat is a distance of 4 2 + 6 2 = 52 units from the location on the route ( 6 , 4 ) . The second
tugboat is a distance of 6 2 + 9 2 = 117 units from the location on the route ( 6 , 4 ) . The first
tugboat is closer than the second tugboat, so the second tugboat will not move to the route that
the ship will take from its starting location to the harbor. The third tugboat is on the harbor and
does not have the same location as another ship, so it will tow the ship during the final leg of the
journey. The fourth tugboat arrives at ( 9 , 6 ) . It is the only boat to reach that location, and that
location is on the route. It will also tow the ship at some point. The tugboat locations and the
path they take to the route can be visualized with the following picture. The numbers represent
the order in which the tugboat appears in the input. There are only 3 tugboats that will be used.
The order of the tugboats that will be used is first ( 6 , 4 ) , fourth ( 9 , 6 ) , and third ( 12 , 8 ) .
The tugboat at position 1 will move to the line at position A to haul the broken ship to point A .
Then tugboat 4 will haul the broken ship for the second leg of the journey. Finally tugboat 3 will
haul the broken ship for the final leg of the journey. The ship names are ShipOnTheWater,
ADerelictBoatTower, and SailingPeacefully Case 2 The broken ship begins at location ( 10 , 0 ) .
The ship is going to the harbor location at location ( 10 , 0 ) There are 6 total tugboats. Below is
a list of the tugboats, their name, where they start, where they could end up on the route, and the
distance they would travel to reach the location on the route. Docked, AlsoDocked, and
OffTheDeepEnd all end up at the same location. The 3rd of those tugboats, OffTheDeepEnd,
would travel farther than the other two, so it is excused from its journey. The 2 nd of the
considered tugboats, AlsoDocked, has a earlier name lexicographically from the other tugboat,
Docked, so AlsoDocked will tow the ship not Docked. The tugboat TooFar would not tow the
ship any distance (it arrives at the same location as the ship starts), so it is also excused. All the
other tugboats have unique locations that result in a valid tow distance. The three tugboats that
will tow are therefore, "InTheMiddle", "AlsoDocked", and "TubGoat". The order in which they
tow the ship is "TubGoat" since it is closest (5 units away), then "InTheMiddle" since it is 10
units away, and finally "AlsoDocked" since it is furthest away at the harbor. Hints Use a Struct:
Store the tugboats in a struct. Use an array of struct to hold all the tugboats, and sort the array.
Comparator Function: Write a function that can return a value (e.g. 1 or -1 ) to represent the
comparison between 2 tugboats. Avoid Floating Points: All the computations can be done
without floating point data types (i.e. floats and doubles) using some "simple" vector geometry. I
recommend using integer-like data types for holding the necessary data. Explanations as to how
to do this follows in the primer below. High Precision: Using an int might not get enough
precision based on the computations that will be done. I recommend using long long ints to hold
on to your values during operations. For example consider using the following to create 2 long
long ints int main() long long int x = 1000000 ; long long int y = 1000000 ; printf(") 11 d  n ", x
y ) ; return 0 ; COMIPARISONS: There are 3 comparisons NEEDED for sorting your value.
They are described in detail below. Geometry Primer Reorientation: It is INCREDIBLY useful
to represent all your points with respect to the ship starting location. To do this you can subtract
from all the points you have (harbor and tugboat locations) the location of your ship. That is
decrement all the x coordinates by the ship's x coordinate and decrement all the y coordinates by
the ship's y coordinate. Vector Point Duality: A vector is data with a magnitude and direction. In
2D space a vector can be expressed using an x and y component. A point has an x and y
component, so points and vectors can be thought of as the same thing. The terms point and
vector will be used interchangeably in the remainder of this primer. The Main Vector: The vector
you will work with the most for this assignment is the one from the boat to the harbor. Since you
should have already reoriented the points with respect to the ship's starting location, this vector
will be the resulting location of the harbor. Point Line Projection: To find where a point lies on a
line (represented by a vector) by moving the shortest distance possible can be found using
projection. Below is an example of a projection (blue vector) of a vector (black dashed) onto
another (solid black). This projection can determine where a tugboat will end up when going to
the route the broken ship will take to the harbor. The projection of a point onto can be found
using the dot product of 2 vectors. The dot product of 2 vectors is the sum of the products of
their components dot ( v 1 , v 2 ) = v 1 x v 2 x + v 1 y v 2 y The reason why this helps is that the
dot product of 2 vectors returns a value that represents the product of the magnitude of the 2
vectors multiplied by the cosine of the angle between the 2 vectors. The cosine of an angle
represents the ratio of the adjacent with respect to the hypotenuse of a right triangle with that
particular angle. The actual projection of v 1 onto v 2 is ( dot ( v 1 , v 2 ) / magnitude ( v 2 ) )
normalized ( v 2 ) For this problem we care more about comparing the distances of these
projections for sorting the points. The actual projections onto the line are not actually required.
For this reason we can ignore BOTH the normalized vector v 2 AND dividing by the magnitude
of v 2 . We only need to consider the dot product, since all tugboats will be projected onto the
same vector. Removing Tugboats that Don't Tug: There will be tugboats that are not actually
going to move our ship anywhere. These tugboats will be the ones that have a non-positive
projection (dot product), since they would be behind our line, OR ones that have a dot product
whose value is more than the projection of the harbor (reoriented with respect to the ship's
starting location) onto the main vector (the vector from the boat to the harbor). Optional Note:
That the dot product of a vector with itself is the square of its magnitude. First Comparison
Summary: The first value that should be compared when sorting the tugboats is the dot product
of the main vector (vector from ship to harbor) with each tugboat vector (vector from ship to
tugboat). Tie Breaking: If 2 tugboats have the same dot product, the tie is broken by determining
which one moves the least distance to the line. I won't get into too many gory details in this
primer, but there is a simpler method. Rather than checking the distance from the tugboat to the
projection on the line (the point the tugboat will reach on the route), instead the distance from the
tugboat to the ship can be used instead. The reason being how the square hypotenuse of a right
triangle is equal to the sum of the squares of the legs of the right triangle. Well the vector from
ship to tugboat is a hypotenuse of the vector from ship to projection and vector from projection
to tugboat. Since 2 tugboats that arrive at the same project have an identical side length the other
side length can be compared by using the hypotenuse instead. Distance Formula: To compute the
distance to a point we use the following x 2 + y 2 Where delta x and delta y are the change in x
and y respectively. Avoiding Square Roots: The square root does not need to be taken since the
square root is an increasing function for positive values. That means that if the square of a
positive number is larger than the square of another positive number, then the first number must
also be larger than the second. Second Comparison Summary: The second value that should be
compared when sorting the tugboats is the square of the distance from the broken ship to the
tugboat. END OF GEOMETRY PRIMER Final Comparison: You need to break ties between
ships that have identical first and second values by the names themselves. You can use strcmp to
compare 2 strings. After Sorting Counting: To count how many boats are valid you can loop
through the tugboats and any boat that has a valid projection value and has a projection value
that is different from the previous contributes to the count by exactly one (since it does not
coincide with an earlier boat). Printing: You can loop the array of tugboats a second time to print
the tugboat names that were valid.

More Related Content

Similar to Need help with this sorting problem- The code I have so far feels ab.pdf

NAVAL ARCHITECTURE- GEOMETRY OF SHIP
NAVAL ARCHITECTURE- GEOMETRY OF SHIPNAVAL ARCHITECTURE- GEOMETRY OF SHIP
NAVAL ARCHITECTURE- GEOMETRY OF SHIPSomasundaramRenganat
 
Retarded potential
Retarded potentialRetarded potential
Retarded potentialSVBIT
 
Is there Life on Mars? a Sample Return Mission Concept
Is there Life on Mars? a Sample Return Mission ConceptIs there Life on Mars? a Sample Return Mission Concept
Is there Life on Mars? a Sample Return Mission ConceptToni Engelhardt
 
Parts of ship
Parts of shipParts of ship
Parts of shipAmadorDe
 
Probabilistic Systems Analysis Homework Help
Probabilistic Systems Analysis Homework HelpProbabilistic Systems Analysis Homework Help
Probabilistic Systems Analysis Homework HelpExcel Homework Help
 

Similar to Need help with this sorting problem- The code I have so far feels ab.pdf (7)

NAVAL ARCHITECTURE- GEOMETRY OF SHIP
NAVAL ARCHITECTURE- GEOMETRY OF SHIPNAVAL ARCHITECTURE- GEOMETRY OF SHIP
NAVAL ARCHITECTURE- GEOMETRY OF SHIP
 
Aus lcu 2000-tarwater
Aus lcu 2000-tarwaterAus lcu 2000-tarwater
Aus lcu 2000-tarwater
 
Retarded potential
Retarded potentialRetarded potential
Retarded potential
 
All
AllAll
All
 
Is there Life on Mars? a Sample Return Mission Concept
Is there Life on Mars? a Sample Return Mission ConceptIs there Life on Mars? a Sample Return Mission Concept
Is there Life on Mars? a Sample Return Mission Concept
 
Parts of ship
Parts of shipParts of ship
Parts of ship
 
Probabilistic Systems Analysis Homework Help
Probabilistic Systems Analysis Homework HelpProbabilistic Systems Analysis Homework Help
Probabilistic Systems Analysis Homework Help
 

More from actexerode

Number of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdfNumber of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdfactexerode
 
Number of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdfNumber of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdfactexerode
 
Nowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdfNowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdfactexerode
 
Now your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdfNow your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdfactexerode
 
Now that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdfNow that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdfactexerode
 
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdfNote- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdfactexerode
 
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdfNow add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdfactexerode
 
Note on vegetarians and type of vegetarians-Must be well explained.pdf
Note on vegetarians and type  of vegetarians-Must be well explained.pdfNote on vegetarians and type  of vegetarians-Must be well explained.pdf
Note on vegetarians and type of vegetarians-Must be well explained.pdfactexerode
 
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdfNot yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdfactexerode
 
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdfNormal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdfactexerode
 
Neman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdfNeman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdfactexerode
 
Night ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdfNight ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdfactexerode
 
Newton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdfNewton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdfactexerode
 
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdfNew DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdfactexerode
 
New devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdfNew devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdfactexerode
 
Networking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdfNetworking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdfactexerode
 
Network standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdfNetwork standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdfactexerode
 
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdfnetflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdfactexerode
 
Netflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdfNetflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdfactexerode
 
Negative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdfNegative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdfactexerode
 

More from actexerode (20)

Number of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdfNumber of years to provide a given return In the information given in.pdf
Number of years to provide a given return In the information given in.pdf
 
Number of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdfNumber of years needed to accumulate a future amount For the following.pdf
Number of years needed to accumulate a future amount For the following.pdf
 
Nowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdfNowadays- we concern about health and nutrition as well as well-balanc.pdf
Nowadays- we concern about health and nutrition as well as well-balanc.pdf
 
Now your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdfNow your job is to write a Kotlin program to maintain the team roster-.pdf
Now your job is to write a Kotlin program to maintain the team roster-.pdf
 
Now that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdfNow that the DFD has been created- it is time to build an object model.pdf
Now that the DFD has been created- it is time to build an object model.pdf
 
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdfNote- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
Note- In C- integer division discards fractions- Ex- 6-4 is 1 (the 0-5.pdf
 
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdfNow add to your GUI to allow the user to select a CUBES project to cla (1).pdf
Now add to your GUI to allow the user to select a CUBES project to cla (1).pdf
 
Note on vegetarians and type of vegetarians-Must be well explained.pdf
Note on vegetarians and type  of vegetarians-Must be well explained.pdfNote on vegetarians and type  of vegetarians-Must be well explained.pdf
Note on vegetarians and type of vegetarians-Must be well explained.pdf
 
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdfNot yet answered Points out of 1-00 Flag question Marshall developed p.pdf
Not yet answered Points out of 1-00 Flag question Marshall developed p.pdf
 
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdfNormal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
Normal red blood cell shapes is a dominant trait- Sicklocell anemia is.pdf
 
Neman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdfNeman- a single parent- quit his job and started a small independent b.pdf
Neman- a single parent- quit his job and started a small independent b.pdf
 
Night ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdfNight ventilation- or night flushing- works best in climates where day.pdf
Night ventilation- or night flushing- works best in climates where day.pdf
 
Newton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdfNewton Industries has a relevant range exlending to 31-800 unts each m.pdf
Newton Industries has a relevant range exlending to 31-800 unts each m.pdf
 
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdfNew DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
New DNA is formed- by copying off RNA molecule templates- when nucleot.pdf
 
New devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdfNew devices and device platforms are continually being released as the.pdf
New devices and device platforms are continually being released as the.pdf
 
Networking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdfNetworking- What are the unix commands - steps to do the following- -.pdf
Networking- What are the unix commands - steps to do the following- -.pdf
 
Network standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdfNetwork standard and technologies use TCP-IP model such as- Network Ac.pdf
Network standard and technologies use TCP-IP model such as- Network Ac.pdf
 
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdfnetflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
netflix uses DIGITAL MEDIA STRATEGIES such as rmail marketing- connect (1).pdf
 
Netflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdfNetflix offers not only streaming entertainment but also a system of a.pdf
Netflix offers not only streaming entertainment but also a system of a.pdf
 
Negative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdfNegative control means a regulator molecule is A)bound- and transcript.pdf
Negative control means a regulator molecule is A)bound- and transcript.pdf
 

Recently uploaded

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 

Recently uploaded (20)

Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 

Need help with this sorting problem- The code I have so far feels ab.pdf

  • 1. Need help with this sorting problem. The code I have so far feels about 70% complete. (I plan to get rid of the qsort function and implement my own merge-sort algo but for now, you can use it.) There are a few errors that prevent it from running. Here is the code I have so far: #include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> #define MAX_N 500000 #define MAX_S 10 struct tugboat { int x, y, dist; char name[21]; }; int cmp(const void* a, const void* b) { const struct tugboat* t1 = (const struct tugboat*) a; const struct tugboat* t2 = (const struct tugboat*) b; if (t1->dist != t2->dist) { return t1->dist - t2->dist; } else { return strcmp(t1->name, t2->name); } } int main() {
  • 2. int xs, ys, xn, yn; scanf("%d%d%d%d", &xs, &ys, &xn, &yn); int n; scanf("%d", &n); struct tugboat tugboats[MAX_N]; int i; for (i = 0; i < n; i++) { scanf("%d%d%s", &tugboats[i].x, &tugboats[i].y, tugboats[i].name); int dx = tugboats[i].x - xs; int dy = tugboats[i].y - ys; tugboats[i].dist = dx * dx + dy * dy; } qsort(tugboats, n, sizeof(struct tugboat), cmp); int num_tugs = 0; char tugs[MAX_N][21]; int prev_x = xs, prev_y = ys; for (i = 0; i < n; i++) { if (tugboats[i].x >= prev_x && tugboats[i].y >= prev_y) { num_tugs++; strcpy(tugs[num_tugs - 1], tugboats[i].name); prev_x = tugboats[i].x; prev_y = tugboats[i].y; }
  • 3. } printf("%dn", num_tugs); for (i = 0; i < num_tugs; i++) { printf("%sn", tugs[i]); } return 0; } Here are the instructions: Tugboat Troubles Objective Give practice with sorting in C. Story The ship's engine has ceased, and now begins the preparations of taking the ship to the harbor for repairs. Luckily it's a straight shot to the harbor. The bad news is that the journey is long. There are several tugboats currently scattered throughout the ocean that can help move the ship to the harbor, but they may have to go out of their way to assist, and taking your crippled ship the full distance is going to be taxing on resources for any 1 particular tugboat. The tugboats have made an agreement. The tugboats will take the shortest path to the direct route that your ship will travel. Once the tugboats are on the route the closest tugboat to your ship will travel from its starting location on your ship's route to your ship's current location. Then the tugboat will tow your ship back to where the tugboat started on your ship's route. When your ship reaches that tugboat's starting location, the tugboat will stop towing your ship and will move back to its original location. After which the process will repeat with the next closest tugboat. If multiple tugboats would arrive at the same location on the ship's route, then only the tugboat that is closest to the location on the ship's route would move to that location. If multiple tugboats are the same distance from the location on the ship's route, then the tugboat with the lexicographically earliest name would move to the route. It is dangerous on the high seas, and you're afraid that your ship may fall victim to pirates that are pretending to be a valid tugboat. Your goal is to produce the names of the tugboats that will tow your ship to the harbor in the order they tow so that your ship. Problem Given the current location of your broken ship, the location of the harbor, and a list of tugboats with both their location and name, determine the number and order in which the tugboats will tow your ship based on the behavior specified above. Input Input will begin with a line containing 4 integers, x s , y s , x h , and y h ( 1 0 6 x s , y s , x h , y h 1 0 6 ) , representing the x and y coordinates of your ship and the x and y coordinates of the harbor respectively. The following line will contain a single integer, n ( 1 n 500 , 000 ) , representing the number of tugboats. The following n lines will each contain a tugboat description (one per line). The tugboat description will contain 2 integers, x and y ( 1 0 6 x , y 1 0 6 ) , representing the x and y coordinates of the tugboat respectively, followed by a string, s , representing the name of the tugboat. The name will contain only upper and lower case characters of which there will be at most 20 . There will be at least 1 tugboat at the location of the harbor. Your ship does not start at the harbor. Output Output should begin with a number k , representing the number of tugboats that will tow your broken
  • 4. ship. Following this should be k lines each containing a single name of a tugboat, the full list comprise the list of the tugboats that will tow your ship in the order they tow your ship. Explanation Case 1 The broken ship begins at location ( 0 , 0 ) . The ship is going to the harbor located at location ( 12 , 8 ) The next line states that there are 4 tugboats in the ocean. The tugboats are at locations ( 10 , 2 ) , ( 0 , 13 ) , ( 12 , 8 ) , and ( 7 , 9 ) . The names of the boats were ShipOnTheWater, KnotGonnaHelp, SailingPeacefully, and ADerelictBoatTower. If the ship were to move onto the line that passes between the points ( 0 , 0 ) and ( 12 , 8 ) , then - The first tugboat (ShipOnTheWater) would end up at point ( 6 , 4 ) - The second tugboat (KnotGonnaHelp) would end up at point ( 6 , 4 ) - The third tugboat (SailingPeacefully) would end up at point ( 12 , 8 ) - The fourth tugboat (ADerelictBoat Tower) would end up at point ( 9 , 6 ) The first and second tugboat have their location coincide. Only 1 will tow the ship. The first tugboat is a distance of 4 2 + 6 2 = 52 units from the location on the route ( 6 , 4 ) . The second tugboat is a distance of 6 2 + 9 2 = 117 units from the location on the route ( 6 , 4 ) . The first tugboat is closer than the second tugboat, so the second tugboat will not move to the route that the ship will take from its starting location to the harbor. The third tugboat is on the harbor and does not have the same location as another ship, so it will tow the ship during the final leg of the journey. The fourth tugboat arrives at ( 9 , 6 ) . It is the only boat to reach that location, and that location is on the route. It will also tow the ship at some point. The tugboat locations and the path they take to the route can be visualized with the following picture. The numbers represent the order in which the tugboat appears in the input. There are only 3 tugboats that will be used. The order of the tugboats that will be used is first ( 6 , 4 ) , fourth ( 9 , 6 ) , and third ( 12 , 8 ) . The tugboat at position 1 will move to the line at position A to haul the broken ship to point A . Then tugboat 4 will haul the broken ship for the second leg of the journey. Finally tugboat 3 will haul the broken ship for the final leg of the journey. The ship names are ShipOnTheWater, ADerelictBoatTower, and SailingPeacefully Case 2 The broken ship begins at location ( 10 , 0 ) . The ship is going to the harbor location at location ( 10 , 0 ) There are 6 total tugboats. Below is a list of the tugboats, their name, where they start, where they could end up on the route, and the distance they would travel to reach the location on the route. Docked, AlsoDocked, and OffTheDeepEnd all end up at the same location. The 3rd of those tugboats, OffTheDeepEnd, would travel farther than the other two, so it is excused from its journey. The 2 nd of the considered tugboats, AlsoDocked, has a earlier name lexicographically from the other tugboat, Docked, so AlsoDocked will tow the ship not Docked. The tugboat TooFar would not tow the ship any distance (it arrives at the same location as the ship starts), so it is also excused. All the other tugboats have unique locations that result in a valid tow distance. The three tugboats that will tow are therefore, "InTheMiddle", "AlsoDocked", and "TubGoat". The order in which they tow the ship is "TubGoat" since it is closest (5 units away), then "InTheMiddle" since it is 10 units away, and finally "AlsoDocked" since it is furthest away at the harbor. Hints Use a Struct: Store the tugboats in a struct. Use an array of struct to hold all the tugboats, and sort the array. Comparator Function: Write a function that can return a value (e.g. 1 or -1 ) to represent the comparison between 2 tugboats. Avoid Floating Points: All the computations can be done without floating point data types (i.e. floats and doubles) using some "simple" vector geometry. I recommend using integer-like data types for holding the necessary data. Explanations as to how to do this follows in the primer below. High Precision: Using an int might not get enough precision based on the computations that will be done. I recommend using long long ints to hold on to your values during operations. For example consider using the following to create 2 long long ints int main() long long int x = 1000000 ; long long int y = 1000000 ; printf(") 11 d n ", x
  • 5. y ) ; return 0 ; COMIPARISONS: There are 3 comparisons NEEDED for sorting your value. They are described in detail below. Geometry Primer Reorientation: It is INCREDIBLY useful to represent all your points with respect to the ship starting location. To do this you can subtract from all the points you have (harbor and tugboat locations) the location of your ship. That is decrement all the x coordinates by the ship's x coordinate and decrement all the y coordinates by the ship's y coordinate. Vector Point Duality: A vector is data with a magnitude and direction. In 2D space a vector can be expressed using an x and y component. A point has an x and y component, so points and vectors can be thought of as the same thing. The terms point and vector will be used interchangeably in the remainder of this primer. The Main Vector: The vector you will work with the most for this assignment is the one from the boat to the harbor. Since you should have already reoriented the points with respect to the ship's starting location, this vector will be the resulting location of the harbor. Point Line Projection: To find where a point lies on a line (represented by a vector) by moving the shortest distance possible can be found using projection. Below is an example of a projection (blue vector) of a vector (black dashed) onto another (solid black). This projection can determine where a tugboat will end up when going to the route the broken ship will take to the harbor. The projection of a point onto can be found using the dot product of 2 vectors. The dot product of 2 vectors is the sum of the products of their components dot ( v 1 , v 2 ) = v 1 x v 2 x + v 1 y v 2 y The reason why this helps is that the dot product of 2 vectors returns a value that represents the product of the magnitude of the 2 vectors multiplied by the cosine of the angle between the 2 vectors. The cosine of an angle represents the ratio of the adjacent with respect to the hypotenuse of a right triangle with that particular angle. The actual projection of v 1 onto v 2 is ( dot ( v 1 , v 2 ) / magnitude ( v 2 ) ) normalized ( v 2 ) For this problem we care more about comparing the distances of these projections for sorting the points. The actual projections onto the line are not actually required. For this reason we can ignore BOTH the normalized vector v 2 AND dividing by the magnitude of v 2 . We only need to consider the dot product, since all tugboats will be projected onto the same vector. Removing Tugboats that Don't Tug: There will be tugboats that are not actually going to move our ship anywhere. These tugboats will be the ones that have a non-positive projection (dot product), since they would be behind our line, OR ones that have a dot product whose value is more than the projection of the harbor (reoriented with respect to the ship's starting location) onto the main vector (the vector from the boat to the harbor). Optional Note: That the dot product of a vector with itself is the square of its magnitude. First Comparison Summary: The first value that should be compared when sorting the tugboats is the dot product of the main vector (vector from ship to harbor) with each tugboat vector (vector from ship to tugboat). Tie Breaking: If 2 tugboats have the same dot product, the tie is broken by determining which one moves the least distance to the line. I won't get into too many gory details in this primer, but there is a simpler method. Rather than checking the distance from the tugboat to the projection on the line (the point the tugboat will reach on the route), instead the distance from the tugboat to the ship can be used instead. The reason being how the square hypotenuse of a right triangle is equal to the sum of the squares of the legs of the right triangle. Well the vector from ship to tugboat is a hypotenuse of the vector from ship to projection and vector from projection to tugboat. Since 2 tugboats that arrive at the same project have an identical side length the other side length can be compared by using the hypotenuse instead. Distance Formula: To compute the distance to a point we use the following x 2 + y 2 Where delta x and delta y are the change in x and y respectively. Avoiding Square Roots: The square root does not need to be taken since the square root is an increasing function for positive values. That means that if the square of a
  • 6. positive number is larger than the square of another positive number, then the first number must also be larger than the second. Second Comparison Summary: The second value that should be compared when sorting the tugboats is the square of the distance from the broken ship to the tugboat. END OF GEOMETRY PRIMER Final Comparison: You need to break ties between ships that have identical first and second values by the names themselves. You can use strcmp to compare 2 strings. After Sorting Counting: To count how many boats are valid you can loop through the tugboats and any boat that has a valid projection value and has a projection value that is different from the previous contributes to the count by exactly one (since it does not coincide with an earlier boat). Printing: You can loop the array of tugboats a second time to print the tugboat names that were valid.