Skip to content
Advertisement

Sort in wave format but starting from specific number

What can be a quick way to sort array in wave format but starting from specific number

for example: starting from point: 4 array: [10,6,0,8,4,2]

output: [4,6,2,8,0,10] enter image description here

and every time output must be randomized, wave in different direction.

output: [4,2,6,0,8,10] enter image description here

Advertisement

Answer

    function rand(min, max) {
        min = Math.ceil(min);
        max = Math.floor(max);
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }
    
    let raznos = 
    [
       0.0061, 0.00611, 0.00609,
      0.00612, 0.00608, 0.00613,
      0.00607, 0.00614, 0.00606,
      0.00615, 0.00605, 0.00616,
      0.00604, 0.00603, 0.00602,
      0.00601
    ];
    
    let start = 0.00610;
    raznos.sort((a, b) => Math.abs(a - start) - Math.abs(b - start) || b - a);
    
    
    if (rand(0,1)){
        let new_raznos = [];
        new_raznos.push(raznos[0]);
    
        for(let i=2; i<=raznos.length; i=i+2){
            if(raznos[i]){
                new_raznos.push(raznos[i]);
            }
            new_raznos.push(raznos[i-1]);
        }
        raznos = new_raznos;
    }
    
    console.log(raznos);

enter image description here enter image description here

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