Skip to content

Instantly share code, notes, and snippets.

@budnik
Last active December 29, 2015 16:38
Show Gist options
  • Save budnik/7698370 to your computer and use it in GitHub Desktop.
Save budnik/7698370 to your computer and use it in GitHub Desktop.
generates N data sets like: [[1,2],[3,4] .. [M-1,M]] and calculates intersection. accepts two integer arguments N, M defaults is 3 and 100
#!/usr/bin/env ruby
require 'csv'
require 'ipaddr'
# Formating:
ff = ->() {
f = ->(a) {a.take(2).map(&IPAddr.method(:new)).map(&:to_i) rescue a.take(2).map(&:to_i) }
f[CSV.parse(self.peek).first]
}
Enumerator.send(:define_method, :foo, ff)
data = ARGV
.map(&File.method(:open))
.map(&:each_line)
# Intersection
result = []
loop do
max = nil
begin
max = data.map(&:foo).map(&:first).max
data.each do |e|
e.next while e.foo.last < max
end
end while max != data.map(&:foo).map(&:first).max
result << [data.map(&:foo).map(&:first).max,
data.map(&:foo).map(&:last).min]
data.each do |e|
e.next while e.foo.last == result.last.last
end
end
puts result.map(&:to_csv).join
#!/usr/bin/env ruby
n = (ARGV.first||3).to_i
m = (ARGV.last||100).to_i
print = ->(a,c=?.){0.upto(m){|i| putc a.map{|r| Range.new(r.first,r.last).include?(i)}.any? ? c : ' ' }; puts}
data = n.times.map{rand(m/2).step(m,rand(19)+1).each_slice(2)}
data.each &print
cursor = []
result = []
loop do
max = data.map(&:peek).map(&:first).max
data.each do |e|
e.next while e.peek.last <= max
end
cursor << [max,max]
result << [data.map(&:peek).map(&:first).max,
data.map(&:peek).map(&:last).min]
data.each do |e|
e.next while e.peek.last == result.last.last
end
end
print[[[0,m]],?=]
pring[cursor, ?^]
print[result, ?x]
$ ./ranges_intersection.rb 3 60
....... ....... ....... .......
................... ...................
................ ................
=============================================================
xxxxxxx xxxxx
$ ./ranges_intersection.rb 3 60
................ ................ .
..... ..... ..... ..... ..... ..... .
................. .
=============================================================
xx xxxxx
$ ./ranges_intersection.rb 2 50
.... .... .... .... .... .
................. .
===================================================
xxxx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment