def sum_loop(n) s = 0 for i in 1..n s = s+i end s end
def divisible(x,y) x%y == 0 end def gd_loop(k,n) while !divisible(k,n) n=n-1 end n end
gd_loop(1234567,1234566)
def sum(n) if n>=2 sum(n-1)+n else 1 end end
def divisible(x,y) x%y == 0 end def sod(k,n) if n>=2 if divisible(k,n) sod(k,n-1)+n else sod(k,n-1) end else 1 end end
def divisible(x,y) x%y == 0 end
def gd(k,n) if divisible(k,n) n else gd(k,n-1) end end
def combination_loop(n,k) c=make2d(n+1,n+1) for i in 0..n c[i][0] = 1 for j in 1..(i-1) c[i][j] = c[i-1][j-1] + c[i-1][j] end c[i][i] = 1 end c[n][k] end
combination_loop(40,32)
def match(s,p) i=0 w=p.length() while submatch(s,i,p,w)< w i=i+1 end i end
def submatch(s,i,p,w) j=0 while j< w && s[(i+j)..(i+j)]==p[j..j] j=j+1 end j end
def match_safe(s,p) i=0 w=p.length() while i<=s.length()-w && submatch(s,i,p,w)< w i=i+1 end if i<=s.length()-w # 見つかった時には何を返す? else # 見つからなかった時には何を返す? end end
match_safe("abra","ra") -> 2 match_safe("abca","ra") -> -1となることを確認してください.
include Math def make1d(n) a=Array.new(n) for i in 0..n-1 a[i]=0 end a end def make2d(h,w) a=Array.new(h) for i in 0..h-1 a[i]=make1d(w) end a end def make3d(h,w,c) a=Array.new(h) for i in 0..h-1 a[i]=make2d(w,c) end a end def show_color_picture() a=make3d(50,50,3) for y in 0..49 for x in 0..49 # 穴を埋める. #a[y][x]にRGB値からなる大きさ3の配列(要素は0から1までの実数)を入れる (1) end end show(a) endたとえば,(1)のところに
a[y][x]=[x/49.0,1.0-y/49.0,1.0]と入れると,
のような図が得られる.
irb(main):014:0> rand(3) => 1 irb(main):015:0> rand(3) => 2 irb(main):016:0> rand(3) => 0実数の乱数は rand() で0.0以上1.0以下の一様乱数が返る.
irb(main):017:0> rand() => 0.65583344076718 irb(main):018:0> rand() => 0.336235732920702 irb(main):019:0> rand() => 0.324077367496
irb(main):020:0> x=2.9 => 2.9 irb(main):021:0> x.to_i() => 2 irb(main):022:0> x=-2.9 => -2.9 irb(main):023:0> x.to_i() => -2四捨五入ではないので,注意が必要.