関数から計算へ


プログラム


  1. 繰り返しによる和の定義

    def sum_loop(n)
      s = 0
      for i in 1..n
        s = s+i
      end
      s
    end
    
  2. 条件を満たす値を探す繰り返し

    load ("./divisible.rb")
    
    def gd_loop(k,n)
      while !divisible(k,n)
        n = n-1
      end
      n
    end
    
  3. 再帰による和の定義

    def sum(n)
      if n >= 2
        sum(n-1) + n
      else
        1
      end
    end
    
  4. 約数の和

    load ("./divisible.rb")
    
    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
    
  5. 条件を満たす値を探す

    load ("./divisible.rb")
    
    def gd(k,n)
      if divisible(k,n)
        n
      else
        gd(k,n-1)
      end
    end
    
  6. カントール集合

    def cantor(n)
      a = make1d(3**n)
      subcantor(a, n, 0)
      a
    end
    
    def subcantor(a, n, x)
      if n==0
        a[x] = 1
      else
        subcantor(a, n-1, x)
        subcantor(a, n-1, x+2*3**(n-1))
      end
    end
    
  7. 配列と繰り返しを使った組み合わせ数の計算

    load ("./make2d.rb")
    
    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
    
  8. 言葉探し

    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
    

2016年11月5日作成
伊知地 宏
Copyright (C) Hiroshi Ichiji, 2016. All rights reserved.