Skip to content

Instantly share code, notes, and snippets.

@marvinahv
Created September 6, 2015 00:27
Show Gist options
  • Save marvinahv/732bfbbe3dd6a8e13190 to your computer and use it in GitHub Desktop.
Save marvinahv/732bfbbe3dd6a8e13190 to your computer and use it in GitHub Desktop.
### If you get a really long list of IP addresses from a text file. Display the top 10 repeated IPs.
def top_10_ips(file)
# Select only the itmes that are repeated more than once
unique = []
repeated = []
File.open(file, 'r').each do |ip_line|
is_repeated = repeated.select{ |repeated_ip| repeated_ip[:ip] == ip_line.strip }
if is_repeated.empty?
is_unique = unique.select{ |unique_ip| unique_ip == ip_line.strip }
if is_unique.empty?
unique << ip_line.strip
else
unique.delete(ip_line.strip)
repeated << { ip: ip_line.strip, times: 2 }
end
else
repeated_ip = is_repeated.first
repeated_ip[:times] += 1
end
end
# Sort the items from more to less times repeated
def my_sort(repeated, index)
a = repeated[index]
b = repeated[index+1]
unless b.nil?
if a[:times] < b[:times]
repeated[index] = b
repeated[index+1] = a
(0..index).reverse_each{ |i| my_sort(repeated, i) }
end
end
end
repeated.each_with_index{ |ip, i| my_sort(repeated, i) }
10.times do |i|
puts repeated[i]
end
end
top_10_ips('ips.txt')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment