Skip to content

Instantly share code, notes, and snippets.

@lygaret
Last active February 19, 2016 06:43
Show Gist options
  • Save lygaret/89b498027fe2aaeb8d02 to your computer and use it in GitHub Desktop.
Save lygaret/89b498027fe2aaeb8d02 to your computer and use it in GitHub Desktop.
find octets in a string with no periods
#!/bin/env ruby
def octet?(str)
(0...256) === str.to_i
end
def octets(str, current = [], output = [])
# bail if there's nothing left to get
if str.nil? || str.empty?
output << current.join(".") if current.length == 4
return
end
# bail early if we've gone past the end
if current.length >= 4 and not str.empty?
return
end
# go 3 characters in, and check for octet
# yes: recurse for the next octet
# no : go back 1 character and check for octet
max = [str.length, 3].min
max.downto(1).each_with_object(output) do |length|
substr = str[0, length]
if octet?(substr)
octets(str[length..-1], current + [substr], output)
end
end
end
$stdin.each_line do |line|
puts "#{line.strip}: #{octets(line.strip)}"
end
@lygaret
Copy link
Author

lygaret commented Feb 19, 2016

[jonathan@beep octets]$ ruby octets.rb 
738493992
738493992: []
34987
34987: ["34.9.8.7", "3.49.8.7", "3.4.98.7", "3.4.9.87"]
8397958
8397958: ["83.97.95.8", "83.97.9.58", "83.9.79.58", "8.39.79.58"]
255355266
255355266: ["255.35.52.66"]
255255255255
255255255255: ["255.255.255.255"]
1111
1111: ["1.1.1.1"]
987654321
987654321: []
87654321
87654321: ["87.65.43.21"]
654321
654321: ["65.43.2.1", "65.4.32.1", "65.4.3.21", "6.54.32.1", "6.54.3.21", "6.5.43.21"]
54321
54321: ["54.3.2.1", "5.43.2.1", "5.4.32.1", "5.4.3.21"]
4321
4321: ["4.3.2.1"]
321
321: []

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment