ProgrammingVery hardCompetitive coding (CP)
After sorting by squared distance from the origin, with ties broken by x ascending, what is printed?
After sorting by squared distance from the origin, with ties broken by x ascending, what is printed?
#include <stdio.h>
#include <stdlib.h>
struct P { int x, y; };
int cmp(const void *a, const void *b) {
const struct P *p = a, *q = b;
int dp = p->x * p->x + p->y * p->y, dq = q->x * q->x + q->y * q->y;
if (dp != dq) return dp - dq;
return p->x - q->x;
}
int main(void) {
struct P v[] = {{3, 4}, {0, 5}, {1, 1}, {2, 2}};
qsort(v, 4, sizeof v[0], cmp);
for (int i = 0; i < 4; i++) printf("%d %d ", v[i].x, v[i].y);
}- A. 1 1 2 2 0 5 3 4
- B. 0 5 1 1 2 2 3 4
- C. 1 1 2 2 3 4 0 5
- D. 2 2 1 1 0 5 3 4
Correct answer: A. 1 1 2 2 0 5 3 4
Squared distances are 25, 25, 2 and 8. After (1,1) and (2,2), the two points at distance squared 25 are ordered by x, so (0,5) precedes (3,4).
More C Programming questions
- How many integers x in 1..255 have exactly four set bits? Compute with this program. c #include <stdio.h> int main(void) { int c = 0; for…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 0xDEAD; int c = 0; unsigned t = x & 0xAAAA; while (t) { c += t & 1u; t…
- How many comparisons does bsearch-style binary search make to find the key 6 in the sorted array 0 to 9? Compute with the program. c…
- What is printed? c #include <stdio.h> int main(void) { int s = 0; for (unsigned i = 0; i < 8; i++) s += (i ^ (i >> 1)) & 1u; printf("%d"…
- What is printed? Assume int is 32 bits. c #include <stdio.h> int main(void) { int a = -3; unsigned b = 2; printf("%u", a b); }
- What is printed? c #include <stdio.h> int main(void) { unsigned a = 7; printf("%u", a / 2 2); }