DEV Community

Cover image for Codewars - Descending Order
Nicolás Bost
Nicolás Bost

Posted on

Codewars - Descending Order

Salutations.

Brick Tamland says hi

I'm posting Codewars challenges and my thought process in this series. I'm using JS and Node 18 whenever possible. Just for the sake of clarity, I'm making fair use of them.

Onto the next challenge from Codewars. In this one, we are tasked with developing a function that takes any integer as input. We have to order the digits from highest to lowest.

I start with this thought:

"Ok, I'll need to split the digits somehow. Maybe I should turn the integer to string first. Then split digits. Then order, then concatenate all, then revert to integer"

And so, it starts with a template:

function descendingOrder(n){

 // stringify
  number = n.toString();

 // split digits
  array = new Array(number.length);
  // code that fills array with digits {}

 //sort
  array.sort()

 // concatenate digits
  reverse = array.join('');

 // back to integer
  n = Number.parseInt(reverse);

  return n;
}
Enter fullscreen mode Exit fullscreen mode

Much letters, such bore. And still not functional. So, what else do we need? Well, a loop that places the digits in the array for starters:

 // split digits
  array = new Array(number.length);
  for(i=0 ; i<number.length ; i  ){
    array[i] = number.at(i);
  }
Enter fullscreen mode Exit fullscreen mode

That should do it. Right?

Goddard is fine

Nope. One tiny little detail. The devil is in the details. And so are bugs. The sort function orders in ascending fashion by default. We need to "revert polarity". In essence, we need this. The default behavior is like this:

(a, b) => a - b
Enter fullscreen mode Exit fullscreen mode

And we need:

(a, b) => b - a
Enter fullscreen mode Exit fullscreen mode

All the ingredients combined:

function descendingOrder(n){
  number = n.toString();
  array = new Array(number.length);
  for(i=0;i<number.length;i  ){
    array[i] = number.at(i);
  }
  array.sort((a,b)=>b-a)
  reverse = array.join('');
  n = Number.parseInt(reverse);
  return n;
}
Enter fullscreen mode Exit fullscreen mode

Not the best, nor the simplest solution. But it does the job.

Cya. Drink water 💧💧💧.

Previous

Top comments (0)