Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of numbers by normal distribution (gaussian distribution)

Having an array of numbers setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9] I'd like to sort this set to have the smallest numbers on the end and beginning and the biggest in the center of the sorted set like this sortedSetNumbers = [0, 2, 3, 9, 7, 3, 1, -2].

const setOfNumbers = [0, 3, 3, 2, 7, 1, -2, 9];
const result = [0, 2, 3, 9, 7, 3, 1, -2];

function sortNormal(a, b) {
  return true; // Please, change this line
}

const sortedSetNumbers = setOfNumbers.sort((a, b) => sortNormal(a, b));



if (sortedSetNumbers === result) {
  console.info('Succeeded Normal Distributed');
} else {
  console.warn('Failed Normal Distribution');
}

console.log(sortedSetNumbers);

I am sure it is possible to sort these numbers with the method Array.prototype.sort(), but how should this sorting function look like?

EDIT: The solution does not have to be solved with .sort(). That was only an idea.

like image 707
Michael Czechowski Avatar asked Jan 27 '23 19:01

Michael Czechowski


1 Answers

This might be the most naive way to do it, but isn't it simply left, right, left, right... after sorting?

const input    = [0, 3, 3, 2, 7, 1, -2, 9];
const expected = [0, 2, 3, 9, 7, 3, 1, -2];

const sorted   = input.slice().sort();
const output   = [];
let side       = true;

while (sorted.length) {
  output[side ? 'unshift' : 'push'](sorted.pop());
  side = !side;
}

console.log(expected.join());
console.log(output.join());

Or simply:

const input  = [0, 3, 3, 2, 7, 1, -2, 9];
const output = input.slice().sort().reduceRight((acc, val, i) => {
  return i % 2 === 0 ? [...acc, val] : [val, ...acc];
}, []);

console.log(output.join());
like image 66
Yoshi Avatar answered Jan 29 '23 09:01

Yoshi