How to resolve the algorithm Sierpinski carpet step by step in the R programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sierpinski carpet step by step in the R programming language
Table of Contents
Problem Statement
Produce a graphical or ASCII-art representation of a Sierpinski carpet of order N.
For example, the Sierpinski carpet of order 3 should look like this: The use of the # character is not rigidly required for ASCII art. The important requirement is the placement of whitespace and non-whitespace characters.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sierpinski carpet step by step in the R programming language
Source code in the r programming language
## Are x,y inside Sierpinski carpet (and where)? (1-yes, 0-no)
inSC <- function(x, y) {
while(TRUE) {
if(!x||!y) {return(1)}
if(x%%3==1&&y%%3==1) {return(0)}
x=x%/%3; y=y%/%3;
} return(0);
}
## Plotting Sierpinski carpet fractal. aev 4/1/17
## ord - order, fn - file name, ttl - plot title, clr - color
pSierpinskiC <- function(ord, fn="", ttl="", clr="navy") {
m=640; abbr="SCR"; dftt="Sierpinski carpet fractal";
n=3^ord-1; M <- matrix(c(0), ncol=n, nrow=n, byrow=TRUE);
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord);
cat(" *** Plot file:", pf,".png", "title:", ttl, "\n");
for(i in 0:n) {
for(j in 0:n) {if(inSC(i,j)) {M[i,j]=1}
}}
plotmat(M, pf, clr, ttl);
cat(" *** END", abbr, date(), "\n");
}
## Executing:
pSierpinskiC(5);
## Plotting Sierpinski carpet fractal v.2. aev 4/2/17
## ord - order, fn - file name, ttl - plot title, clr - color
pSierpinskiC2 <- function(ord, fn="", ttl="", clr="brown") {
m=640; abbr="SCR2"; dftt="Sierpinski carpet fractal v.2";
cat(" *** START", abbr, date(), "\n");
if(fn=="") {pf=paste0(abbr,"o", ord)} else {pf=paste0(fn, ".png")};
if(ttl!="") {dftt=ttl}; ttl=paste0(dftt,", order ", ord);
cat(" *** Plot file:", pf,".png", "title:", ttl, "\n");
S = matrix(1,1,1);
for (i in 1:ord) {
Q = cbind(S,S,S); R = cbind(S,0*S,S); S = rbind(Q,R,Q);
}
plotmat(S, pf, clr, ttl);
cat(" *** END", abbr, date(), "\n");
}
## Executing:
pSierpinskiC2(5);
You may also check:How to resolve the algorithm Monty Hall problem step by step in the Standard ML programming language
You may also check:How to resolve the algorithm Maximum triangle path sum step by step in the REXX programming language
You may also check:How to resolve the algorithm Egyptian division step by step in the Erlang programming language
You may also check:How to resolve the algorithm Terminal control/Ringing the terminal bell step by step in the J programming language
You may also check:How to resolve the algorithm Animate a pendulum step by step in the Icon and Unicon programming language