Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array of numbers as 'Bell', 'Curve' and 'Wave'

Given this list of values:

print samples

[5.0, 5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.5, 9.0, 9.5, 10.0]

I need to generate n number of values for a new array length of n. This can be achieved like this.

for i in range(n):
        My_array.append(random.choice(samples))

Now My_array needs sorting, in 5 ways: Increasing, Decreasing, 'Bell', 'Curve', 'Wave'

The first 2 can be achieved by

print sorted(My_array,reverse=False)
[5.5, 6.0, 6.5, 7.0, 7.5, 8.0, 8.0, 9.0, 9.0, 10.0]


print sorted(My_array,reverse=True)
[10.0, 9.0, 9.0, 8.0, 8.0, 7.5, 7.0, 6.5, 6.0, 5.5]

How about the remaining three?

In the above example, 'Bell' should be like this:

[5.5,6.5,7.0,8.0,9.0,10.0,9.0,8.0,7.5,6.0]

while 'Curve' should be like this:

[9.0,8.0,7.0,6.5,5.5,6.0,7.5,8.0,9.0,10.0]

and 'Wave' should be like this (it really doesn't matter if it's cos-like or sine-like wave):

[5.5,7.0, 8.0, 10.0, 9.0,7.5, 6.0, 6.5, 8.0, 9.0]
like image 911
DimitrisD Avatar asked Oct 19 '25 15:10

DimitrisD


2 Answers

For the Wave you can follow Alex L's idea: you divide the sorted array into d subarrays, sort some of them in ascending order and others in descending order and then put them together:

def wave_sort(array, num_peaks=None, start_ascending=True):
    """Sorts the elements of `array` in a sine or cosine manner.

    :param array: The array to be sorted.
    :param num_peaks: The number of (low and high) peaks in the resultant array
    :param start_ascending: If True the result is sin-like, otherwise cos-like.
    """
    if num_peaks is None:
        num_peaks = len(array) // 6
    sorted_ar = sorted(array)
    subarrays = [sorted_ar[i::num_peaks] for i in range(num_peaks)]
    for i, subarray in enumerate(subarrays, start=int(not start_ascending)):
        if i % 2:
            # subarrays are in ascending order already!
            subarray.reverse()
    return sum(subarrays, [])

An other way to achieve the same, would be to split the sorted array into d/2 subarrays and for each subarray obtain a Bell using Alex L solution, and then put them together.

like image 171
Bakuriu Avatar answered Oct 21 '25 05:10

Bakuriu


"Bell" could be two sub arrays, one sorted increasing other decreasing. Proceed with this idea for the other problems.

like image 43
PeterMmm Avatar answered Oct 21 '25 06:10

PeterMmm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!