Check if an array is descending, ascending or not sorted?

后端 未结 7 1703
不思量自难忘°
不思量自难忘° 2021-01-18 09:01

I\'m just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build. I got this question for homework but I c

7条回答
  •  失恋的感觉
    2021-01-18 09:56

    Actually we may do even more by creating an Array method like natureOf which can tell us more about the nature of the array than just ascending, descendig or flat. Array.natureOf() shall give us a value between -1 and 1. If it is -1 the array is fully descending and 1 would mean fully ascending of course. Any value inbetween would give us the inclination of the array. As you would guess 0 would mean totally random or flat. (it's fairly easy to insert the logic to distinguish random from flat if that's also needed)

    Array.natureOf = function(a){
                       var nature = a.reduce((n,e,i,a) => i && a[i-1] !== e ? a[i-1] < e ? (n.asc++, n)
                                                                                         : (n.dsc++, n)
                                                                            : n, {asc:0, dsc:0});
                       return (nature.asc - nature.dsc) / (a.length-1);
                     };
    var arr = [1,2,3,4,5,6,7,8,9,10,7,11,13,14,15],
        brr = Array.from({length:2000000}, _ => ~~(Math.random()*1000000000));
    
    console.log(`The nature of "arr" array is ${Array.natureOf(arr)}`);
    console.log(`The nature of "brr" array is ${Array.natureOf(brr)}`);

提交回复
热议问题