Ruby: Hash - Sorting/Adjusting Duplicate Values and Storing Back with Key? -


so having bit of issue here deciding tools use solve problem. rather complex problem best describe it.

at moment have relationship of values gathered , stored in hash. hash way of doing things can changed else think better. used hash keep relationship important.

so like:

key  -> value  1456 -> 1 1532 -> 50 1892 -> 2 1092 -> 5 1487 -> 10 5641 -> 5 1234 -> 2 1687 -> 1 

my goal here take values, , adjust them there no duplicates, , place adjusted values in appropriate relationship key. not want duplicate values deleted, want them changed in way there no duplicates anymore. (duplicates in example above are: 1 , 2)

as side note here summary of few important things keep in mind situation:

  • the relationship between key-value pairs (must know value key)
  • not having duplicate values
  • you cannot delete key-value pair, change value.
  • the order of values lowest highest important

normally have no trouble sorting array of integers, in case relationship other values giving me lot of trouble this.

input = { 1456 => 1,   1532 => 50,   1892 => 2,   1092 => 5,   1487 => 10,   5641 => 5,   1234 => 2,   1687 => 1 }  values = input.sort_by { |a,b| b }.map { |a,b| } # => [1456, 1687, 1892, 1234, 1092, 5641, 1487, 1532] hash[*values.flat_map.with_index(1) { |a,i| [a,i] }] # => {1456=>1, 1687=>2, 1892=>3, 1234=>4, 1092=>5, 5641=>6, 1487=>7, 1532=>8} 

all necessary information contained in values array.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -