Skip to content

Instantly share code, notes, and snippets.

@eagletmt
Created December 29, 2009 17:51
Show Gist options
  • Save eagletmt/265461 to your computer and use it in GitHub Desktop.
Save eagletmt/265461 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby1.9
# coding: utf-8
input = ARGF.gets.chomp
# 24 区切りに分ける
points = [0] * 10
input.each_byte { |c|
points[(268-c)/24] += 1
}
print '++++++[>++++['
mems = []
points.each_with_index { |c, i|
if c != 0
print ">#{'-'*i}"
mems << 256-i*24
end
}
print "#{'<'*mems.size}-]<-]>>"
ptr = 0
input.each_byte { |c|
# ポインタの移動 + インクリメント,デクリメントが最小になるのを探す
i = ptr
min = c - mems[ptr]
mems.each_with_index { |m, j|
if (c - m).abs + (ptr - j).abs < min.abs + (ptr - i).abs
min = c - m
i = j
end
}
if ptr < i
print '>'*(i-ptr)
elsif ptr > i
print '<'*(ptr-i)
end
cmd = ''
if min < 0
cmd = '-'
elsif min > 0
cmd = '+'
end
count = min.abs
if count > 15 and i == mems.size-1
# 15より大きいときは勘と経験による頭悪いパターンマッチ
case count
when 16
print ">++++[<#{cmd*4}>-]<"
when 17
print ">++++[<#{cmd*4}>-]<#{cmd}"
when 18
print ">++++++[<#{cmd*3}>-]<"
when 19
print ">+++++[<#{cmd*4}>-]<#{cmd}"
when 20
print ">+++++[<#{cmd*4}>-]<"
when 21
print ">+++++++[<#{cmd*3}>-]<"
when 22
print ">+++++++[<#{cmd*3}>-]<#{cmd}"
when 23
print ">+++++++[<#{cmd*3}>-]<#{cmd*2}"
when 24
print ">++++++[<#{cmd*4}>-]<"
when 25
print ">+++++[<#{cmd*5}>-]<"
else
puts "\nえー…: #{count}"
exit 1
end
else
# 15より少ないときはそのまま
print cmd*count
end
print '.'
ptr = i
mems[ptr] += min
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment