It is Monday. It is a beautiful sunny day in the Twin Cities Area. All is well so far.
I picked up the next Java challenge Java BigDecimal from HackerRank.
The challenge requires for one to sort in descending order a specified set of numbers provided as strings. You can read the entire description at the HackerRank web site.
It seems that one is supposed to write the solution inside the main() program.
Let’s take a look at what the testing scaffolding provided looks like:
import java.math.BigDecimal; import java.util.*; class Solution{ public static void main(String []args){ //Input Scanner sc= new Scanner(System.in); int n=sc.nextInt(); String []s=new String[n+2]; for(int i=0;i<n;i++){ s[i]=sc.next(); } sc.close(); //Output for(int i=0;i<n;i++) { System.out.println(s[i]); } } }
As usual the input is provided, but the code allocates an array of strings of size n + 2 given only n strings with numbers to re read. Not sure the purpose of it.
I used the test cases as follows:
9 -100 50 0 56.6 90 0.12 .12 02.34 000.000 {-truncated-} 90 56.6 50 02.34 0.12 .12 0 000.000 -100 10 123 45 766 324324 .324 0.325 -234 4546 100 0 324324 4546 766 123 100 45 0.325 .324 0 -234
My solution inserted between the input and output sections follows:
// **** sort values in descending order **** Arrays.sort(s, 0, n, new Comparator<Object>() { public int compare(Object o1, Object o2) { BigDecimal bd1 = new BigDecimal((String)o1); BigDecimal bd2 = new BigDecimal((String)o2); return bd2.compareTo(bd1); } });
The string values are sorted in place using a comparator that converts two strings into BigDecimal values and then compares them.
If interested my complete solution is in my GitHub repository.
If you have comments or questions regarding this or any other post in this blog, or if you would like to recommend a challenge, or if you need some help with any phase in the software development process of a product or service please let me know. All requests will be kept confidential if requested.
Keep on reading and experimenting. Remember that the best code is the one that is elegant and simple.
John
Please follow me on Twitter: @john_canessa