0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

if文を使わないFizzBuzz

Last updated at Posted at 2018-12-28

まずは普通のFizzBuzz

fizzbuzz.sh
#!/bin/sh
for i in {1..100}
do
  if [ $(( ${i} % 3 )) -eq 0 ]; then
    s="Fizz"
  else
    unset s
  fi
  if [ $(( ${i} % 5 )) -eq 0 ]; then
    s=${s}"Buzz"
  fi
  echo ${s-${i}}
done

工夫したのはecho ${s-${i}}です。この-は、左側が定義済みであれば左側の値を使用、未定義であれば右側の値を使用する、というシェル変数独特の記法です。実質的にこの中に判断文が入っているわけですが、見た目はif文を減らすことができます。

if文を使わないFizzBuzz

そこで思いついたのが、こんなプログラムです。

fizzbuzz2.sh
#!/bin/sh
for i in `seq 3 3 100`
do
  a[${i}]="Fizz"
done

for i in `seq 5 5 100`
do
  a[${i}]=${a[${i}]}"Buzz"
done

for i in {1..100}
do
  echo ${a[${i}]-${i}}
done

一応、if文は使っていません。-が実質的に判断文といえばそうですが。
判断文を全く無くすとしたら、最初に配列の中身を全部数字で埋めるんでしょうね。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?