Untitled

mail@pastecode.io avatar
unknown
ruby
2 months ago
942 B
2
Indexable
Never
def lilysHomework(arr)
    sorted_arr = arr.sort
    reversed_sorted_arr = sorted_arr.reverse
    
    # original arr = [2, 5, 3, 1]
    # sorted_arr = [1, 2, 3, 5]
    # reversed_sorted_arr = [5, 3, 2, 1]
  
    # Both ASC and DESC sorting are fine
    default_mapping = {}
    reverse_mapping = {}
  
    # Fill both mappings
    arr.each_with_index do |value, i|
      default_mapping[value] = sorted_arr[i]
      reverse_mapping[value] = reversed_sorted_arr[i]
    end
    
    # default_mapping = {2=>1, 5=>2, 3=>3, 1=>5}
    # reverse_mapping = {2=>5, 5=>3, 3=>2, 1=>1}
  
    # Choose the way with min swaps count
    [swaps_count(default_mapping), swaps_count(reverse_mapping)].min
end
  
def swaps_count(mapping)
    swaps = 0
    mapping.each do |key, value|
      while key != value
        swaps += 1
        mapping[key] = mapping[value]
        mapping[value] = value
        value = mapping[key]
      end
    end
    swaps
end
Leave a Comment