Module: Diffable

Included in:
Array, String
Defined in:
lib/array_diff.rb

Instance Method Summary collapse

Instance Method Details

#diff(b) ⇒ Object



197
198
199
# File 'lib/array_diff.rb', line 197

def diff(b)
  ArrayDiff.new(self, b)
end

#patch(diff) ⇒ Object



244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
# File 'lib/array_diff.rb', line 244

def patch(diff)
  newary = nil
  if diff.difftype == String
    newary = diff.difftype.new('')
  else
    newary = diff.difftype.new
  end
  ai = 0
  bi = 0
  diff.diffs.each { |d|
    d.each { |mod|
  case mod[0]
  when '-'
    while ai < mod[1]
      newary << self[ai]
      ai += 1
      bi += 1
    end
    ai += 1
  when '+'
    while bi < mod[1]
      newary << self[ai]
      ai += 1
      bi += 1
    end
    newary << mod[2]
    bi += 1
  else
    raise "Unknown diff action"
  end
    }
  }
  while ai < self.length
    newary << self[ai]
    ai += 1
    bi += 1
  end
  return newary
end

#replacenextlarger(value, high = nil) ⇒ Object



217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/array_diff.rb', line 217

def replacenextlarger(value, high = nil)
  high ||= self.length
  if self.empty? || value > self[-1]
    push value
    return high
  end
  # binary search for replacement point
  low = 0
  while low < high
    index = (high+low)/2
    found = self[index]
    return nil if value == found
    if value > found
  low = index + 1
    else
  high = index
    end
  end

  self[low] = value
  # $stderr << "replace #{value} : 0/#{low}/#{init_high} (#{steps} steps) (#{init_high-low} off )\n"
  # $stderr.puts self.inspect
  #gets
  #p length - low
  return low
end

#reverse_hash(range = (0...self.length)) ⇒ Object

Create a hash that maps elements of the array to arrays of indices where the elements are found.



204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/array_diff.rb', line 204

def reverse_hash(range = (0...self.length))
  revmap = {}
  range.each { |i|
    elem = self[i]
    if revmap.has_key? elem
  revmap[elem].push i
    else
  revmap[elem] = [i]
    end
  }
  return revmap
end