Comparator reverseOrder understanding in Java8 - java-8

Comparator.comparing(SortedClass::getValue)
.thenComparing(( SortedClass::getKey),reverseOrder());
VS
Comparator.comparing(SortedClass::getValue)
.reversed()
.thenComparing(SortedClass::getKey).reversed();
Looking at the second code it seems like final value will be Sort by Value descending then sort by key descending again. But surprisingly both expression giving me the same result. Any explanation why ?

Maybe it's easier to see if you split into two statements.
Comparator<SortedClass> comp1 = Comparator.comparing(SortedClass::getValue)
.reversed()
.thenComparing(SortedClass::getKey);
Comparator<SortedClass> comp2 = comp1.reversed();
comp1 is "sort by value descending, then by key ascending". So when you reverse that, of course you get "sort by value ascending, then by key descending".

Related

How to sort an array in Ruby

Persoane = []
Nume = gets
Persoane.push Nume.split(",")
puts Persoane.sort
I am trying to get an user to input carachters that get split into substrings which get inserted in an array, then the program would output the strings in alphabetical order. It doesnt seem to work and I just get the array's contents, like so:
PS C:\Users\Lenovo\Desktop\Ruby> ruby "c:\Users\Lenovo\Desktop\Ruby\ruby-test.rb"
Scrie numele la persoane
Andrei,Codrin,Bradea
Andrei
Codrin
Bradea
PS C:\Users\Lenovo\Desktop\Ruby>
you can do this :
Nume = gets
puts Nume.split(",").sort
or in 1 line
array = gets.chomp.split(",").sort
The error is because of your use of push. Let's assume that you define the constant Nume by
Nume='Andrei,Codrin,Bradea'
Then, Nume.split(',') would return the Array ['Andrei', 'Codrin', 'Bradea']. When you do a Persoane.push, the whole array is added to your array Persoane as a single element. Therefore, Persoane contains only one Element, as you can verify when you do a
p Persoane
If you sort a one-element array, the result will also be just that one element - there is nothing to sort.
What you can do is using concat instead of push. This would result in Persoane being a 3-element array which can be sorted.
I'm not sure you need use constants here
If you don't need keep user input and use it somewhere, you can just chain methods like this
persons = gets.chomp.split(",").sort
For something a little different, let's not split at all.
people = gets.scan(/[^,]+/).map(&:strip).sort
This will avoid problems like multiple commas in a row yielding empty strings. Of course, you could also avoid that with:
people = gets.split(/\,+/).map(&:strip).sort

sort values of an orddict

In order to extract the values (records) of an orddict as a sorted list, tried this:
-module(test).
-compile(export_all).
-record(node, {name="", cost=0}).
test() ->
List = orddict:append("A",#node{name="A",cost=1},
orddict:append("B",#node{name="B",cost=2},
orddict:new())),
lists:sort(fun({_,A},{_,B}) -> A#node.cost =< B#node.cost end,
orddict:to_list(List)).
The sort fails with exception error: {badrecord,node}.
What would be the correct syntax?
Solved:
The correct insertion method is orddict:store/2 instead of orddict:append/2. Then the pattern {_,A} matches for the comparison function.
The correct syntax is:
lists:sort(fun({_,[A]},{_,[B]}) -> A#node.cost =< B#node.cost end,
orddict:to_list(List)).
I not found note about this in documentation,but you can look in source code of module.
As #Pascal write in comments the reason is that orddict:append/3 is a function provided to append a value to an existing Key/Value pair where Value must be a list. In the use case, the key doesn't exist, so the pair is created and the Value append to an empty list.
Btw, you always can print and compare real and expected result.
io:format("~p~n",[orddict:to_list(List)])
For your example that is:
[{"A",[{node,"A",1}]},{"B",[{node,"B",2}]}]

Python 3.3.2 - Sorting a List, While Disregarding Vowels

I am creating a program that sorts a list (Just like list.sort()) but it won't count vowels. Here is what I mean:
I have a list of... ['acd', 'ibc', 'ebb', 'zzaeib'] or something similar. A normal sort program would give this as the result: ['acd', 'ebb', 'ibc', 'zzaeib']. My sort will need to disregard the vowels, sort it, and the put the vowels back in and return the resulting list. For example, it would see the list above as ['cd', 'bc', 'bb', 'zzb']. It would then sort it (['bb', 'bc', 'cd', 'zzb']) and put the vowels back in (['ebb', 'ibc', 'acd', 'zzaeib']).
Here are the differences:
Normal sort: ['acd', 'ebb', 'ibc', 'zzaeib']
Custom sort: ['ebb', 'ibc', 'acd', 'zzaeib']
I know I can use the key feature of sort (list.sort(key=whatever_key)), but I cannot see a way to do this. Thanks in advance.
Rob.
I know I can use the key feature of sort
Yep, you were almost there.
import re
new_list = sorted(l, key=lambda s: re.sub('[aioue]', '', s))

Sort an array by value

I have an array like this:
array = ["git-hw-abcd", "svn-hw", "svn-hw-design","git-hw"]
If I do array.sort I would basically get an ascending sort like this
["git-hw", "git-hw-abcd", "svn-hw", "svn-hw-design"]
Would like to sort the array by the values "svn-hw" and "git-hw" to appear as the first and second elements of the array so that I would get:
[ "svn-hw","git-hw",... then the rest of the values]
Any help would be appreciated.
Try this
* sorting on length(as sort criteria is not specified)
["git-hw-abcd", "svn-hw", "svn-hw-design","git-hw"].sort{|a,b| a.length <=> b.length}
It returns
["git-hw", "svn-hw", "git-hw-abcd", "svn-hw-design"]
array.sort{|a,b| a.split("-h")[1]<=>b.split("-h")[1]}
this is what you want
#Hivltg
try the length order using this :array= [ "svn-hw", "git-hw-abcd","git-hw", "svn-hw-design", "git-hw-bassics"]
you will find out the problem.
Not exactly sure how you're ordering, but here's an example of using a block to sort
array.sort{|a,b| a[4..-1] <=> b[4..-1]}

how to sort a treemap using bubble sort?

27527-683
27525-1179
27525-1571
27525-1813
27525-4911
27526-1303
27526-3641
27525-3989
27525-4083
27525-4670
27526-4102
27526-558
27527-2411
27527-4342
this is the list of key where it is declared as string in a map
then i want to sort it in ascending order.
how can i use a bubble sorting method inside a map?
where the value of the key is a list.
in order to get :
27525-1179
27525-1571
27525-1813
27525-3989
27525-4083
27525-4670
27525-4911
27526-558
27526-1303
27526-3641
27526-4102
27527-683
27527-2411
27527-4342
You should be able to just perform an in-order traversal on your tree. Bu if you insist here is what you would do.
keyList = yourTreeMap.getKeys();
for(i = keyList.length-1; i > 0; i--)
for(j = 0; j < i; j++)
if (keyList[j] > keyList[j+1]) keyList.swap(j, j+1);
Since you don't specify a lnaguage, I present psuedocode.
In general you just use the same bubble sort algorithm as normal it's just your comparison condition that's tweaked here to look at both the key and the value to determine what is greater than what, that is compare the keys first and if they're equal then compare the values if the keys don't match then use the difference in the values to get your result of swap or don't swap. Bubble sort is bad efficiency-wise though if you're using this in a real world scenario.
Jon got the post in before me but basically what he wrote looks right except you'd want a complex condition for the if within the nested loop, like
if(key1<key2)
keyList.swap(i,j)
else if(keyList[key1]<keyList[key2])
keyList.swap(i,j)
of course as he also stated how these keys/values are actually extracted/used will depend on the language, which is lacking in the question or tags.

Resources