Certainly! Below is a Ruby method that perturbs a sorted list by moving each item up to ±N positions from its original position randomly:
def perturb_list(sorted_list, n)
# Create an array to store the perturbed list
perturbed_list = Array.new(sorted_list.size)
# Create an array of indices to track available positions
available_positions = (0...sorted_list.size).to_a
sorted_list.each_with_index do |item, original_index|
# Calculate the range of possible new positions
min_index = [original_index - n, 0].max
max_index = [original_index + n, sorted_list.size - 1].min
# Filter available positions within the range
possible_positions = available_positions.select { |pos| pos.between?(min_index, max_index) }
# Randomly select a new position from the possible positions
new_position = possible_positions.sample
# Place the item in the new position
perturbed_list[new_position] = item
# Remove the new position from available positions
available_positions.delete(new_position)
end
perturbed_list
end
# Example usage
sorted_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 2
perturbed = perturb_list(sorted_list, n)
puts "Original list: #{sorted_list}"
puts "Perturbed list: #{perturbed}"
Explanation:
-
Input Parameters:
sorted_list: The original sorted list.
n: The maximum number of positions an item can move up or down.
-
Logic:
- For each item in the list, calculate the range of possible new positions (
min_index to max_index).
- Filter the available positions to ensure no overlap and maintain uniqueness.
- Randomly select a new position from the valid range and place the item there.
- Remove the chosen position from the list of available positions to avoid conflicts.
-
Output:
- The method returns a new list where each item has been perturbed by up to ±N positions.
This ensures that the perturbation respects the constraints and avoids overwriting or duplicating items.