Last active
February 19, 2016 06:43
-
-
Save lygaret/89b498027fe2aaeb8d02 to your computer and use it in GitHub Desktop.
find octets in a string with no periods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
Author
lygaret
commented
Feb 19, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment