请求提供移除数据库中重复及重复模式价格记录的算法
Got it, let's tackle this duplicate price record cleanup problem. The goal here is to strip out consecutive entries with identical prices—since they don't add any meaningful data to your price trend tracking, right? We only need to keep the records where the price actually shifts.
Core Approach
We'll build a cleaned list of records by only retaining entries where the price differs from the last saved record. Consecutive duplicates get discarded because they don't reflect a meaningful change in the price trend.
Solution Code
Record = Struct.new(:id, :created_at, :price) records = [ Record.new(1, Date.parse('2017-01-01'), 150_000), Record.new(2, Date.parse('2017-01-02'), 150_000), Record.new(3, Date.parse('2017-01-03'), 130_000), Record.new(4, Date.parse('2017-01-04'), 140_000), Record.new(5, Date.parse('2017-01-05'), 140_000), Record.new(6, Date.parse('2017-01-06'), 130_000) ] # Build cleaned list by keeping only price-change records cleaned_records = records.inject([]) do |result, record| # Add the record if it's the first entry, or if price differs from last saved entry if result.empty? || record.price != result.last.price result << record end result end # Print the cleaned output cleaned_records.each do |r| puts "ID: #{r.id}, Date: #{r.created_at}, Price: #{r.price}" end
What This Does
- We use Ruby's
injectmethod to iterate through the records and build our cleaned array. - For each record, we check two things: if we're dealing with the first entry, or if the current price is different from the last record we kept.
- If either condition is true, we add the record to our result list—otherwise, we skip it.
Sample Output
ID: 1, Date: 2017-01-01, Price: 150000 ID: 3, Date: 2017-01-03, Price: 130000 ID: 4, Date: 2017-01-04, Price: 140000 ID: 6, Date: 2017-01-06, Price: 130000
Edge Cases Covered
- All records have the same price: Only the first record is kept (no redundant duplicates).
- Single record: The record is returned as-is, no changes needed.
- Non-consecutive duplicates: Records with the same price but separated by different prices are both kept—since this reflects a price change back to a previous value, which is useful for trend tracking.
Optional: Keep the Latest Consecutive Duplicate
If you'd rather retain the last entry in a sequence of identical prices (instead of the earliest), adjust the logic to replace the last entry in the result array until a price change is detected:
cleaned_records = records.inject([]) do |result, record| if result.empty? || record.price != result.last.price result << record else # Replace the last entry with the current one to keep the latest date for same price result[-1] = record end result end
This version will give you the most recent date for each consecutive price sequence.
内容的提问来源于stack exchange,提问作者Niels Kristian

