Skip to content

Instantly share code, notes, and snippets.

@utgwkk
Last active May 24, 2016 08:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utgwkk/0f06da4130b97f13ae66 to your computer and use it in GitHub Desktop.
Save utgwkk/0f06da4130b97f13ae66 to your computer and use it in GitHub Desktop.
Brainf*ck
# 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