LoginSignup
1
0

More than 5 years have passed since last update.

Rで作るシェルピンスキーのギャスケット(三角形)

Last updated at Posted at 2017-06-22

最新の更新

コードの美しさを犠牲に「三角形をくり抜いて作っていく」仕様の獲得と画像出力時の余分な目盛りなどの削除を行った。

main
Sierpinski.gasket <- function(x=3) {    # x = depth
    plot(0,0,main="Sierpinski gasket",xlab=" ",ylab=" ",xaxt="n",yaxt="n")
    y <- c(0,1,-1,-1,1,-1)              # Set the position
    polygon(c(y[1],y[3],y[5]),c(y[2],y[4],y[6]),col="gray")
    if(x > 0) {
        Sierpinski.gasket.triangle(x-1,y)
    }
}

上記で使用している関数(サブルーチン)

sub
Sierpinski.gasket.triangle <- function(x,y) {
    xy <- c((y[1]+y[3])/2,(y[2]+y[4])/2,(y[1]+y[5])/2,(y[2]+y[6])/2,(y[3]+y[5])/2,(y[4]+y[6])/2)
    polygon(c(xy[1],xy[3],xy[5]),c(xy[2],xy[4],xy[6]),col="white",border=F)
    if(x > 0) {
        Recall(x-1,c(y[1],y[2],xy[1],xy[2],xy[3],xy[4]))
        Recall(x-1,c(xy[1],xy[2],y[3],y[4],xy[5],xy[6]))
        Recall(x-1,c(xy[3],xy[4],xy[5],xy[6],y[5],y[6]))
    }
}

Sierpinski gasket_triangle.png


一つ前のバージョン

変数xは自然数のみ有効となり、描画する。
Wikipediaによると正確には「三角形をくり抜いて作っていく」もののようだが、
前回のプログラムは三角形の外線のみを描いている。

main(old)
Sierpinski.gasket <- function(x){    # x = depth
    plot(10,10)                      # Make a drawing space
    y <- c(10,14,6,6,14,6)           # Set the position
    if(x>0){
        Sierpinski.gasket.triangle(x-1,y)
    }
}

上記で使用している関数(サブルーチン)

sub(old)
Sierpinski.gasket.triangle <- function(x,y){
    polygon(c(y[1],y[3],y[5]),c(y[2],y[4],y[6]))
    y1 <- c(y[1],y[2],(y[1]+y[3])/2,(y[2]+y[4])/2,(y[1]+y[5])/2,(y[2]+y[6])/2)
    y2 <- c((y[1]+y[3])/2,(y[2]+y[4])/2,y[3],y[4],(y[3]+y[5])/2,(y[4]+y[6])/2)
    y3 <- c((y[1]+y[5])/2,(y[2]+y[6])/2,(y[3]+y[5])/2,(y[4]+y[6])/2,y[5],y[6])
    if(x>0){
        Recall(x-1,y1)
        Recall(x-1,y2)
        Recall(x-1,y3)
    }
}

Sierpinski_gasket_triangle.png

深度の変更機能を維持したまま、もっと簡略に書けないものだろうか。

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0