That’s pretty strange what you don’t have any code on C#…
or use cmp_to_key
sorted_tasks = sorted(arr, key=cmp_to_key(lambda t1, t2: t1[1] - t2[1])))
sorted_tasks = [(‘Buy grocery’, 3), (‘Cook dinner’, 5)]
where is ‘arr’ defined? Is this an error?
for c++:
solution.cc: In function ‘void print_sorted_array(std::vector)’:
solution.cc:11:5: error: ‘put_words’ was not declared in this scope
11 | put_words(nums);
| ^~~~~~~~~
Its failed because print and get function are declared after print_sorted_array function it should be before.
c# is added
Something not obvious is that the first Java example is using a Google library called Guava to use Lists.newArrayList
that you probably won’t have access to in your interviews.
In order to use this in your code you’d have to add Guava as a dependency and import:
import com.google.common.collect.Lists;
I’m not sure why they used this, but here’s what an alternative with the Java library looks like, they used it before in the previous line:
List<Task> tasks = Arrays.asList(
new Task("Cook dinner", 5),
new Task("Buy grocery", 3)
);
The first Java example also won’t compile correctly because it’s calling compareTo()
on the priority
getter for an int
. Updating it to use private Integer priority
will fix it:
Collections.sort(tasks, (Task t1, Task t2) -> t1.getPriority().compareTo(t2.getPriority()));
which can then could be shortened in Java 8:
Collections.sort(tasks, Comparator.comparing(Task::getPriority));
Alternatively, you can retain the primitive int priority
since Integer
allows for nullability and update the comparator:
Comparator<Task> comp = (Task t1, Task t2) -> {
return Integer.compare(t1.getPriority(), t2.getPriority());
};
This can also be shortened in Java 8 to:
Comparator<Task> comp = Comparator.comparingInt(Task::getPriority);
but knowing the previous solution still helpful.