Skip to main content

Examples 2

  1. This is a script that calculates the Fibonacci numbers, using an iterative algorithm:

    fibo.sh
    #!/bin/bash

    N=$1
    if [[ -z $N ]]; then
    echo "Usage: $0 <n>" >&2
    exit 1
    fi

    [[ $N == 0 ]] && echo 0 && exit
    [[ $N == 1 ]] && echo 1 && exit

    f0=0
    f1=1
    for ((i=1; i<N; i++)); do
    fib=$((f0 + f1))
    f0=$f1
    f1=$fib
    done
    echo $f1
    vim fibo.sh
    ./fibo.sh
    for i in {0..10}; do ./fibo.sh $i; done
    ./fibo.sh 100
  2. This is a script that solves the problem of Towers of Hanoi, using a recursive algorithm:

    hanoi.sh
    #!/bin/bash

    solve_hanoi() {
    local disks=$1 src=$2 dst=$3 aux=$4
    if ((disks > 0)); then
    solve_hanoi $((disks - 1)) $src $aux $dst
    echo "move $src --> $dst"
    ((nr_moves++))
    solve_hanoi $((disks - 1)) $aux $dst $src
    fi
    }

    read -p "Towers of Hanoi. How many disks? " disks

    nr_moves=0 # start with no moves
    solve_hanoi $disks 'src' 'dst' 'aux'

    echo "It took $nr_moves moves to solve Towers for $disks disks."
    vim hanoi.sh
    ./hanoi.sh <<< 0
    ./hanoi.sh <<< 1
    ./hanoi.sh <<< 2
    ./hanoi.sh <<< 3
    ./hanoi.sh <<< 4
    ./hanoi.sh <<< 5
Loading asciinema cast...