E
Erwin
As per Ruby CookBook, I learnt how to sort a simple array by
frequency :
def sort_by_frequency_descending
histogram = inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}
sort_by { |x| [histogram[x] * -1, x]}
end
[1,2,3,4,1,2,4,8,1,4,9,16].sort_by_frequency_descending
# => [1, 1, 1, 4, 4, 4, 2, 2, 3, 8, 9, 16]
Q1: how should I modify this method, to manipulate more complex
array,
like [ [1, 1, a] ,[2 , 2, b] ,[ 3, 4, c] , [ 4, 5, d] , [1, 2, e] ,
[ 2, 1, f] , [.....
where I should sort on the first and second value of each element
this sort_by_frequency_descending is a prelude comparing sucessive
items of the array, once it is sorted :
b_start = [ [1.0, 1.5, a1] , [1.0, 1.5, a2], [1.0, 1.5, a3], [1.0,
1.5, a4], [2.1, 2.5, a5], [2.1, 2.5, a6], [2.1, 2.5, a7], [4.6, 4.2,
a8], [4.6, 4.2, a9], [4.6, 4.2, a10], [8.3, 8.4, a11], [8.3, 8.4,
a12], [9.5, 9.3, a13], [16.8, 16.7, a14] ]
when an item has first & second values identical to first & second
values of previous item, then a proc should be applied to both values
of second item to modify them ( * by random)
b_start[i+1][0] == b_start[0] && _start[i+1][1] == b_start[1]
Q2: I am not yet fluent with this kind of complex process (beyond my
present readin status of ruby cookbook...)...
I'll appreciate any help
frequency :
def sort_by_frequency_descending
histogram = inject(Hash.new(0)) { |hash, x| hash[x] += 1; hash}
sort_by { |x| [histogram[x] * -1, x]}
end
[1,2,3,4,1,2,4,8,1,4,9,16].sort_by_frequency_descending
# => [1, 1, 1, 4, 4, 4, 2, 2, 3, 8, 9, 16]
Q1: how should I modify this method, to manipulate more complex
array,
like [ [1, 1, a] ,[2 , 2, b] ,[ 3, 4, c] , [ 4, 5, d] , [1, 2, e] ,
[ 2, 1, f] , [.....
where I should sort on the first and second value of each element
this sort_by_frequency_descending is a prelude comparing sucessive
items of the array, once it is sorted :
b_start = [ [1.0, 1.5, a1] , [1.0, 1.5, a2], [1.0, 1.5, a3], [1.0,
1.5, a4], [2.1, 2.5, a5], [2.1, 2.5, a6], [2.1, 2.5, a7], [4.6, 4.2,
a8], [4.6, 4.2, a9], [4.6, 4.2, a10], [8.3, 8.4, a11], [8.3, 8.4,
a12], [9.5, 9.3, a13], [16.8, 16.7, a14] ]
when an item has first & second values identical to first & second
values of previous item, then a proc should be applied to both values
of second item to modify them ( * by random)
b_start[i+1][0] == b_start[0] && _start[i+1][1] == b_start[1]
Q2: I am not yet fluent with this kind of complex process (beyond my
present readin status of ruby cookbook...)...
I'll appreciate any help