Skip to content

Instantly share code, notes, and snippets.

@suyash
Last active April 5, 2016 12:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save suyash/3aad5b76edbc51e1e713ca1f4b09d007 to your computer and use it in GitHub Desktop.
Save suyash/3aad5b76edbc51e1e713ca1f4b09d007 to your computer and use it in GitHub Desktop.
Y fractal

Y fractal for a given number of levels

for 3 levels:

\ / \ / \ / \ /
 |   |   |   |
 \   /   \   /
  \ /     \ /
   |       |
   |       |
   \       /
    \     /
     \   /
      \ /
       |
       |
       |
       |
#include <iostream>
void print (int level) {
for (int i = 0 ; i < level ; i += 1) {
int p = 1 << i;
int c = 1 << (level - i);
int sp = p - 1;
int s = (1 << (i + 1)) - 1;
int sn = (1 << (i + 2)) - 1;
// top part
for (int k = 0 ; k < p ; k += 1) {
std::cout << std::string(sp + k, ' ');
for (int j = 0 ; j < c - 1 ; j += 1) {
if (j & 1) std::cout << '/' << std::string(s + 2 * k, ' ');
else std::cout << '\\' << std::string(s - 2 * k, ' ');
}
std::cout << '/' << std::endl;
}
// bottom part
for (int k = 0 ; k < p ; k += 1) {
std::cout << std::string(s, ' ');
for (int j = 1 ; j < c >> 1 ; j += 1) {
std::cout << '|' << std::string(sn, ' ');
}
std::cout << '|' << std::endl;
}
}
}
int main () {
int n = 0;
std::cout << "Enter levels: ";
std::cin >> n;
print(n);
return 0;
}
package main
import (
"fmt"
"strconv"
)
func print(levels int) {
for i := 0; i < levels; i += 1 {
p := 1 << uint32(i)
c := 1 << uint32(levels-i)
sp := p - 1
s := (1 << uint32(i+1)) - 1
sn := (1 << uint32(i+2)) - 1
// top
for k := 0; k < p; k++ {
if sp+k > 0 {
fmt.Printf("%"+strconv.Itoa(sp+k)+"s", " ")
}
for j := 0; j < c-1; j++ {
if j&1 == 1 {
fmt.Printf("/%"+strconv.Itoa(s+(k<<1))+"s", " ")
} else {
fmt.Printf("\\%"+strconv.Itoa(s-(k<<1))+"s", " ")
}
}
fmt.Println("/")
}
// bottom
for k := 0; k < p; k++ {
fmt.Printf("%"+strconv.Itoa(s)+"s", " ")
for j := 1; j < c>>1; j++ {
fmt.Printf("|%"+strconv.Itoa(sn)+"s", " ")
}
fmt.Println("|")
}
}
}
func main() {
fmt.Print("Enter Levels: ")
var levels int
fmt.Scan(&levels)
print(levels)
}
printf "Enter levels: "
read level
spaces () {
for (( x = 0; x < $1; x += 1 ))
do
printf " "
done
}
print () {
for (( i = 0; i < level; i += 1 ))
do
p=$((1 << i))
c=$((1 << $((level - i))))
sp=$((p - 1))
s=$(($((1 << $((i + 1)))) - 1))
sn=$(($((1 << $((i + 2)))) - 1))
# top part
for (( k = 0; k < p; k += 1 ))
do
spaces $((sp + k))
for (( j = 0; j < $((c - 1)); j += 1 ))
do
if [ $((j % 2)) -eq 1 ]
then
printf "/"
spaces $((s + 2 * k))
else
printf "\\"
spaces $((s - 2 * k))
fi
done
printf "/\n"
done
# bottom part
for (( k = 0; k < p; k += 1 ))
do
spaces $s
for (( j = 1; j < $((c >> 1)); j += 1 ))
do
printf "|"
spaces $sn
done
printf "|\n"
done
done
}
print "$level"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment