Bash コンソールに三角形を描く

Bash コンソールに三角形を描く

次のようにネストされたループを使用して三角形を描きたいと思いますbash

    /\
   /  \
  /    \
 /      \
/________\

これは私のスクリプトです。

#!/bin/bash
read -r -p "Enter depth of pyramid: " n
echo "You enetered level: $n"
s=0
space=n
for((i=1;i<=n;i++))
do
  space=$((space-1)) #calculate how many spaces should be printed before /
  for((j=1;j<=space;j++))
  do
    echo -n " " #print spaces on the same line before printing /
  done
  for((k=1;k<=i;k++))
  do
    if ((i==1))
    then
      echo -n "/\ " #print /\ on the same line
      echo -n " " #print space after /\ on the same line
    elif((k==1))
    then
      echo -n "/" #print / on the same line
    elif((k==i))
    then
      for((l=1;l<=k+s;l++))
      do
        echo -n " " #print spaces on the same line before printing /\
      done
      s=$((s+1)) #as pyramid expands at bottom, so we need to recalculate inner spaces
      echo -n "\ " #print \ on the same line
    fi
  done
  echo -e #print new line after each row
done

短いバージョンを見つけるのに役立ちます。

ベストアンサー1

$ ./script.sh
Size: 5
    /\
   /  \
  /    \
 /      \
/________\
#!/bin/bash

read -p 'Size: ' sz

for (( i = 0; i < sz-1; ++i )); do
        printf '%*s/%*s\\\n' "$((sz-i-1))" "" "$((2*i))" ""
done

if [[ $sz -gt 1 ]]; then
        printf '/%s\\\n' "$( yes '_' | head -n "$((2*i))" | tr -d '\n' )"
fi

私は選んだいいえ遅くて不要なので、入れ子になったループを使ってください。三角形の各ビットは、printf現在の行に基づいて文字間の間隔を指定する形式を使用して印刷されます。/\i

一番下の行は特別で、三角形のサイズが許容できる場合にのみ印刷されます。

エマルジョン:

おすすめ記事