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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay