Skip to content
Advertisement

Rearrange substrings using two criteria [closed]

Given a String:

JavaScript

I need to sort its substrings first by numbers (in descending order) and then by letters, so that the result of the sort has the following form:

JavaScript

Advertisement

Answer

To solve, the problem must be broken down into subproblems:

  1. Break down the input string into substrings
  2. Collect each substring into a list
  3. Create a comparator that compares the last (numeric) portion of the (sub)string and sorts them in descending order, and then by the beginning portion in ascending order
  4. Convert the list of substrings back into a string

Break down the input string into substrings

JavaScript

Collect each substring into a list

JavaScript

The code above will iterate through all of the groups that matched the regex pattern and adds them to a list.

Create a comparator

JavaScript

The comparator I created compares the last portion of the substrings (after the dash) and sorts them in descending order (reversed()). Then, the intermediate result is sorted in ascending order from the beginning of the substring up to the dash. Basically it sorts the intermediate result in alphabetical order since the substrings start with a letter.

Convert the list of substrings back into a string

JavaScript

I created a test program to run this:

JavaScript

Which results in the following:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement