Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- array = [211, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
- array = [211, 200, 199, 198, 197, 196 ... ]
- def change_em(arr)
- dup_indices = arr.each_index.group_by { |i| arr[i] }.values.flat_map { |a| a.drop(1) }
- puts "dup_indices = #{dup_indices}"
- last = arr.first + 1
- arr.each_index.map { |i| last = dup_indices.include?(i) ? last-1 : arr[i] }
- end
- change_em [10, 8, 5, 5, 7]
- #=> dup_indices = [3]
- #=> [10, 8, 5, 4, 7]
- change_em [10, 8, 7, 5, 5]
- #=> dup_indices = [4]
- #=> [10, 8, 7, 5, 4]
- change_em [211, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 196]
- #=> dup_indices = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
- #=> [211, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190, 196]
- def f(arr, dups = [])
- return deduct_dups(dups) if arr.empty?
- if arr[0] != arr[1] # Not duplicates
- if dups.empty? # No duplicates to insert
- [arr[0]] + f(arr[1..-1])
- else # Insert duplicates
- deduct_dups(dups) + f(arr[1..-1])
- end
- else # Duplicate found, add the first element to the dup array
- f(arr[1..-1], dups.push(arr[0]))
- end
- end
- def deduct_dups(dups)
- return [] if dups.empty?
- (dups.first - dups.length..dups.first).to_a.reverse
- end
- p f [211, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200, 200]
- # => [211, 200, 199, 198, 197, 196, 195, 194, 193, 192, 191, 190]
- p f [10, 8, 5, 5, 7].sort.reverse
- # => [10, 8, 5, 4, 7]
- p f [9, 6, 6, 5, 5, 4, 4, 3, 3, 3, 2, 2, 1].sort.reverse
- # => [9, 6, 5, 5, 4, 4, 3, 3, 2, 1, 2, 1, 1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement