Hacker Rank Linux Shell (Bash)
Looping and Skipping
A Personalized Echo
Solution
1 2
read name echo "Welcome $name"
-
Looping with Numbers
Solution
1 2 3 4
for X in {1..50} do echo $X done
-
The World of Numbers
Solution
1 2 3 4 5 6
read X read Y echo $((X+Y)) echo $((X-Y)) echo $((X*Y)) echo $((X/Y))
-
Comparing Numbers
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
read X read Y if (( $X > $Y )) then echo "X is greater than Y" fi if (( $X == $Y)) then echo "X is equal to Y" fi if(( $X < $Y)) then echo "X is less than Y" fi
-
Getting started with conditionals
Solution
1 2 3 4 5 6 7 8
read word if [[($word == 'y') || ($word == 'Y')]] then echo "YES" elif [[($word == 'n') || ($word == 'N')]] then echo "NO" fi
-
More on Conditionals
Solution
1 2 3 4 5 6 7 8 9 10 11 12
read x read y read z if [[($x == $y) && ($y == $z)]] then echo "EQUILATERAL" elif [[($x == $y) || ($x == $z) || ($y == $z)]] then echo "ISOSCELES" else echo "SCALENE" fi
-
Arithmetic Operations
Solution
1 2
read x printf "%.3f\n" `echo "$x" | bc -l`
-
Compute the Average
Solution
1 2 3 4 5 6 7 8 9 10
read num ctr=$num sum=0 while [ $ctr -gt 0 ] do read x sum=$((sum + x)) ctr=$((ctr - 1)) done printf "%.3f\n" `echo "$sum/$num" | bc -l`
-
Functions and Fractals - Recursive Trees - Bash!
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
declare -A matrix num_rows=63 num_columns=100 declare -a roots roots[0]=50 for ((i=1;i<=num_rows;i++)) do for ((j=1;j<=num_columns;j++)) do matrix[$i,$j]='_' done done read n j=63 len=16 for ((i=1; i<=n; i++)) do lim=$((${#roots[@]}-1)) elems=${#roots[@]} old_j=$j for((k=0; k<=lim; k++)) do pos=${roots[$k]} #print the trunk for((m=0; m<=len-1; m++)) do matrix[$j,$pos]='1' ((j--)) done #print the branches for((m=1; m<=len; m++)) do matrix[$j,$((pos-m))]='1' matrix[$j,$((pos+m))]='1' ((j--)) done roots=("${roots[@]}" "$((pos-m+1))" "$((pos+m-1))" ) if (( $k < $lim )) then j=$old_j fi done for((k=0; k<$elems; k++)) do unset roots[$k] done roots=( "${roots[@]}" ) len=$((len/2)) done # print the matrix for ((i=1;i<=num_rows;i++)) do for ((j=1;j<=num_columns;j++)) do printf ${matrix[$i,$j]} done printf "\n" done
Comments
Post a Comment