codingforeveryone/js

new-member-37: Reverse Sort

Closed this issue · 2 comments

jwld commented

Problem Specification
Write a function that takes an array of numbers and sorts them, but in reverse - so it should sort by the final digit first, then the second last, then the third last etc.

Example
reverseSort([123, 45, 1179, 3359, 133, 613]) --> [613, 123, 133, 45, 3359, 1179]

Idly looking through these and found this one really interesting. Not sure if you're still looking at it, but here's an answer:

var reverseSort = function(arr) {
    /* Simple check for valid arrays */
    if (arr.filter(function(obj) {
        return typeof(obj) === 'number';
    }).length) {
        /* Split each number into an array of its own constituent numbers */
        arr = arr.map(function(item) {
            var output = [];
            item = item.toString();
            for (var i = 0; i < item.length; i++) {
                output.push(Number(item.charAt(i)));
            }
            return output
        });
        
        /* Reassemble an array of numbers back into a single number */
        var reassemble = function(array) {
            return Number(array.join(""));
        };
        
        /* Initialise a results array with the first item from the input array */
        var res = [arr[0]];
        
        /* Loop through both lists, followed by the numbers in each respective item */
        mainloop: for (var i = 1; i < arr.length; i++) {
            for (var j = 0; j < res.length; j++) {
                /* Remember we need to loop _backwards_ through these numbers */
                for (var k = arr[i].length - 1, l = res[j].length - 1; k >= 0 && l >= 0; k--, l--) {
                    if (arr[i][k] < res[j][l]) {
                        res.splice(j, 0, arr[i]);
                        continue mainloop;
                    } 
                }
            }
            /* This is the biggest number we've seen, so add it to the end of the results array */
            res.push(arr[i]);
        }
        return res.map(reassemble);
    } else {
        /* Could do something better here… */
        throw new Error("You need to provide a valid array containing one or more integers.");
    }
};
jwld commented

Sorry for the delay in responding to this - I have intermittent internet access at the moment!

Great solution - I clearly underestimated how tricky that was. I'll close the issue - I believe you're meant to push the solution to practice with git, and then post a new problem (if you want 👍 ). Cheers!