Skip to content

Instantly share code, notes, and snippets.

@shoyan
Last active December 23, 2015 17:29
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 shoyan/6669516 to your computer and use it in GitHub Desktop.
Save shoyan/6669516 to your computer and use it in GitHub Desktop.
パスカルの三角形をRubyで実装してみました。PascalsTriangle.new.run(10)で数字を出力、PascalsTriangle.new.run(40, 'fractal')でフラクタル図形を描画します。(fractalの場合はCOUNTを40くらいにするとよいです)
# encoding: utf-8
class PascalsTriangle
@@count= 10
@@list = []
def create(list)
sum = []
i = 1
while i < list.size
sum.push(list[i - 1] + list[i])
i+=1
end
return [1] + sum + [1]
end
def show(list, mode='normal')
i = 0
list.each do |x|
space = ((@@count - i) / 2) * 2
space-=1 if i % 2 == 0
space.times {print " "}
case mode
when 'fractal'
self.show_fractal(x)
else
self.show_normal(x)
end
i+=1
end
end
def show_normal(list)
print list * " "
print "\n\n"
end
def show_fractal(list)
list.each_index do |i|
if list[i] % 2 == 0 then
list[i] = "●"
else
list[i] = "○"
end
end
print list * " "
print "\n"
end
def run(count=10, mode='normal')
@@count = count
@@count.times do |x|
@@list[x] = [1] if x == 0
@@list[x] = [1, 1] if x == 1
next if x <= 1
@@list[x] = self.create(@@list[x - 1])
end
self.show(@@list, mode)
end
end
PascalsTriangle.new.run(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment