Skip to content

Instantly share code, notes, and snippets.

@dijikul
Last active August 29, 2015 14:19
Show Gist options
  • Save dijikul/7eab3d42105f0e58a8f7 to your computer and use it in GitHub Desktop.
Save dijikul/7eab3d42105f0e58a8f7 to your computer and use it in GitHub Desktop.
The Chuck Norris Problem in Ruby
$MESSAGE = gets.chomp
def make_zeros(count)
zeros = ""
count.times do
zeros += "0"
end
return zeros
end
def convert_unary(msg)
bits = ""
#STDERR.puts msg.length
msg.length.times do |b|
bits += msg[b].to_s.ord.to_s(2).rjust(7, "0")
end
STDERR.puts msg + " => " + bits + " => " + bits.size.to_s + " digits"
result = ""
k = 1
last = bits[0]
result = ( bits[0] == "0" ) ? "00 " : "0 "
# changing start changes first count?
for i in 1..bits.size do
if bits[i] != last then
result += make_zeros(k)
k = 1
last = bits[i]
if bits[i] == "0" then
result += " 00 "
elsif bits[i] == "1" then
result += " 0 "
end
# below doesn't work - nfiw - debug?
#result = result + ( ( $bits[i] == 0) ? " 00 " : " 0 " )
else
k += 1
end
end
result = result + make_zeros(k)
return result
end
text_msg = $MESSAGE
#binary_msg = $MESSAGE.ord.to_s(2)
unary_msg = convert_unary(text_msg)
puts unary_msg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment