Skip to content

Instantly share code, notes, and snippets.

@dmig
Created March 16, 2021 15:46
Show Gist options
  • Save dmig/4ff6effe275607aba4ae155e9bcf629d to your computer and use it in GitHub Desktop.
Save dmig/4ff6effe275607aba4ae155e9bcf629d to your computer and use it in GitHub Desktop.
Fractal tree: a solution for a beautiful task from HackerRank (https://www.hackerrank.com/challenges/fractal-trees-all/problem)
# same implemented in python as a POC
N=5
print('_' * 100)
offset = 0
for i in range(5-N):
offset += 2 ** i
for j in range(2 ** i * 2):
print('_' * 100)
for i in range(6-N, 6):
points=2 ** (i - 1)
cnt = 2 ** (5 - i)
spc = 2 ** i - 1
for j in range(points):
print('_' * 18, end='')
for k in range(cnt):
print('_' * offset, end='')
print('1' + ('_' * spc) + '1', end='')
print('_' * offset, end='')
print('_', end='')
print('_' * 18)
offset += 1
spc -= 2
for j in range(points):
print('_' * 18, end='')
for k in range(cnt):
print('_' * offset, end='')
print('1', end='')
print('_' * (offset + 1), end='')
print('_' * 18)
#! /bin/bash
read N
# N=4
printf '_%.0s' {1..100}
echo
offset=0
for ((i=0; i<5-N; i++)); do
offset=$((offset + 2 ** i))
for ((j=0; j<2 ** i * 2; j++)); do
printf '_%.0s' {1..100}
echo
done
done
for ((i=6-N; i<6; i++)); do
points=$((2 ** (i - 1)))
cnt=$((2 ** (5-i)))
spc=$((2 ** i - 1))
for ((j=0; j<points; j++)); do
# printf '%2d, %2d, %2d' $points $cnt $j
printf '_%.0s' {1..18}
for ((k=0; k<cnt; k++)); do
if [[ $offset -gt 0 ]]; then
printf '_%.0s' $(seq 1 $offset)
fi
printf '1'
printf '_%.0s' $(seq 1 $spc)
printf '1'
if [[ $offset -gt 0 ]]; then
printf '_%.0s' $(seq 1 $offset)
fi
printf '_'
done
printf '_%.0s' {1..18}
echo
offset=$((offset + 1))
spc=$((spc - 2))
done
for ((j=0; j<points; j++)); do
printf '_%.0s' {1..18}
for ((k=0; k<cnt; k++)); do
printf '_%.0s' $(seq 1 $offset)
printf '1'
printf '_%.0s' $(seq 1 $offset)
printf '_'
done
printf '_%.0s' {1..18}
echo
done
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment