第3章の練習,投票


条件分岐 - 場合分けを使った計算

def max(x,y)
  if y < x
    x
  else
    y
  end
end

3通りの場合分け

def sign(x)
    if x < 0
        -1
    else
        if 0 < x
            1          # not(x < 0) and 0 < x
        else
            0          # not(x < 0) and not (0 < x)
        end
    end
end

どれが正しいか?

xの値が7、yの値が5、zの値が3であるとして
  1. x < y
  2. x <= y
  3. y != z
  4. z > x
  5. z == x

どれが正しいか?

xの値が7、yの値が5、zの値が3であるとして
  1. x < y
  2. x <= y
  3. x < y && y != z
  4. x <= y || y == z
  5. !(y == z)

次の結果は何?

def is_even(x)
    x%2 == 0
end
def tnpo(n)
    if is_even(n)
        n/2
    else
        3*n + 1
   end
end
irb(main):001:0> tnpo(tnpo(tnpo(7)))
  1. 1
  2. 4
  3. 7
  4. 11
  5. 34

文字列

s="abra"
t="cadabra"
u=s+t
"123"+"456"
s.length()
(s+t).length()
s[0..0]
s[1..2]
t[1..(t.length()-1)]

次の結果は何?

irb(main):001:0> s="abra"
=> "abra"
irb(main):002:0> t = "cadabra"
=> "cadabra"
irb(main):003:0> t[1..3]+s[1..2]
  1. 5
  2. "ab"
  3. "adabr"
  4. "adabbra"
  5. "cadabraabra"

与えられた大きさの配列を作る

load("./make1d.rb")
make1d(10)
load("./make2d.rb")
make2d(4,2)

繰り返しの例

def squares (n)
  a=make1d(n)
  for i in 0..(n-1)
    a[i] = i * i
  end
  a
end
load("./make1d.rb")
squares(10)

繰り返しの例(ドイツ国旗)

def german()
  image = make2d(3, 5)
  for x in (0..4)
    image[0][x]=[0,0,0] # black
    image[1][x]=[1,0,0] # red
    image[2][x]=[1,1,0] # yellow
  end
  image
end
load("./make2d.rb")
show(german())

2重の繰り返し

load("./make2d.rb")
def sphere(s)
  image = make2d(s,s)
  for y in 0..(s-1) 
    for x in 0..(s-1)
      image[y][x] = b(s,x,y)
    end	
  end	
  image
end

練習

# 教科書 P.10 練習1.2(a)のdistance
def distance(x,y,u,v)
  # ここにdistanceの定義を書く
end

def b(s,x,y)
  # ここにbの定義を書く
end


練習

show(sphere(20)) を実行して表示される画像を確めよ。なお,下の絵は show(sphere(100)) で作成したもの.


進捗状況の確認


練習


進捗状況の確認

  1. 両方できた。
  2. solutionsだけ。
  3. medianだけ。
  4. まだ何もできていない。