Last active
May 24, 2016 08:57
-
-
Save utgwkk/0f06da4130b97f13ae66 to your computer and use it in GitHub Desktop.
Brainf*ck
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
# coding: utf-8 | |
# bf.rb | |
# 入力された文字列を出力する Brainf*ck コードを出力する | |
def f(num) | |
if num <= 13 then | |
return false | |
end | |
lst = [] | |
cnt = 0 | |
2.upto(Math.sqrt(num).to_i) do |i| | |
if num % i == 0 then | |
lst[cnt] = [i, num / i] | |
cnt += 1 | |
end | |
end | |
if lst.empty? then | |
return false | |
end | |
lst.sort!{|a,b|a[0]+a[1]<=>b[0]+b[1]} | |
return lst[0] | |
end | |
if not ARGV[0] then | |
print " > " | |
input = gets.chomp.bytes.to_a | |
else | |
input = ARGV[0].bytes.to_a | |
end | |
input.size.times do |a| | |
if a == 0 then | |
lst = f(input[a]) | |
if not lst then | |
if input[0] <= 13 then | |
print ">", "+"*input[0] | |
else | |
1.upto(input[0]) do |count| | |
lste = f(input[0]-count) | |
if lste then | |
print "+"*lste[0], "[>", "+"*lste[1], "<-]>", "+"*count | |
break | |
else | |
lste = f(input[0]+count) | |
if lste then | |
print "+"*lste[0], "[>", "+"*lste[1], "<-]>", "-"*count | |
break | |
end | |
end | |
end | |
end | |
else | |
print "+"*lst[0], "[>", "+"*lst[1], "<-]>" | |
end | |
else | |
delta = input[a] - input[a-1] | |
delta_abs = delta.abs | |
lst = f(delta_abs) | |
if delta < 0 then | |
if not lst then | |
if delta_abs <= 13 then | |
print "-"*delta_abs | |
else | |
1.upto(delta_abs) do |count| | |
lste = f(delta_abs-count) | |
if lste then | |
print "<", "+"*lste[0], "[>", "-"*lste[1], "<-]>", "-"*count | |
break | |
else | |
lste = f(delta_abs+count) | |
if lste then | |
print "<", "+"*lste[0], "[>", "-"*lste[1], "<-]>", "+"*count | |
break | |
end | |
end | |
end | |
end | |
else | |
print "<", "+"*lst[0], "[>", "-"*lst[1], "<-]>" | |
end | |
elsif delta > 0 then | |
if not lst then | |
if delta_abs <= 13 then | |
print "+"*delta_abs | |
else | |
1.upto(delta_abs) do |count| | |
lste = f(delta_abs-count) | |
if lste then | |
print "<", "+"*lste[0], "[>", "+"*lste[1], "<-]>", "+"*count | |
break | |
else | |
lste = f(delta_abs+count) | |
if lste then | |
print "<", "+"*lste[0], "[>", "+"*lste[1], "<-]>", "-"*count | |
break | |
end | |
end | |
end | |
end | |
else | |
print "<", "+"*lst[0], "[>", "+"*lst[1], "<-]>" | |
end | |
end | |
end | |
print "." | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment