Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
37
Task/Hailstone-sequence/UNIX-Shell/hailstone-sequence-1.sh
Normal file
37
Task/Hailstone-sequence/UNIX-Shell/hailstone-sequence-1.sh
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
#!/bin/bash
|
||||
# seq is the array genereated by hailstone
|
||||
# index is used for seq
|
||||
declare -a seq
|
||||
declare -i index
|
||||
|
||||
# Create a routine to generate the hailstone sequence for a number
|
||||
hailstone () {
|
||||
unset seq index
|
||||
seq[$((index++))]=$((n=$1))
|
||||
while [ $n -ne 1 ]; do
|
||||
[ $((n % 2)) -eq 1 ] && ((n=n*3+1)) || ((n=n/2))
|
||||
seq[$((index++))]=$n
|
||||
done
|
||||
}
|
||||
|
||||
# Use the routine to show that the hailstone sequence for the number 27
|
||||
# has 112 elements starting with 27, 82, 41, 124 and ending with 8, 4, 2, 1
|
||||
i=27
|
||||
hailstone $i
|
||||
echo "$i: ${#seq[@]}"
|
||||
echo "${seq[@]:0:4} ... ${seq[@]:(-4):4}"
|
||||
|
||||
# Show the number less than 100,000 which has the longest hailstone
|
||||
# sequence together with that sequences length.
|
||||
# (But don't show the actual sequence)!
|
||||
max=0
|
||||
maxlen=0
|
||||
for ((i=1;i<100000;i++)); do
|
||||
hailstone $i
|
||||
if [ $((len=${#seq[@]})) -gt $maxlen ]; then
|
||||
max=$i
|
||||
maxlen=$len
|
||||
fi
|
||||
done
|
||||
|
||||
echo "${max} has a hailstone sequence length of ${maxlen}"
|
||||
30
Task/Hailstone-sequence/UNIX-Shell/hailstone-sequence-2.sh
Normal file
30
Task/Hailstone-sequence/UNIX-Shell/hailstone-sequence-2.sh
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
# Outputs a hailstone sequence from $1, with one element per line.
|
||||
# Clobbers $n.
|
||||
hailstone() {
|
||||
n=`expr "$1" + 0`
|
||||
eval "test $? -lt 2 || return $?" # $n must be integer.
|
||||
|
||||
echo $n
|
||||
while test $n -ne 1; do
|
||||
if expr $n % 2 >/dev/null; then
|
||||
n=`expr 3 \* $n + 1`
|
||||
else
|
||||
n=`expr $n / 2`
|
||||
fi
|
||||
echo $n
|
||||
done
|
||||
}
|
||||
|
||||
set -- `hailstone 27`
|
||||
echo "Hailstone sequence from 27 has $# elements:"
|
||||
first="$1, $2, $3, $4"
|
||||
shift `expr $# - 4`
|
||||
echo " $first, ..., $1, $2, $3, $4"
|
||||
|
||||
i=1 max=0 maxlen=0
|
||||
while test $i -lt 1000; do
|
||||
len=`hailstone $i | wc -l | tr -d ' '`
|
||||
test $len -gt $maxlen && max=$i maxlen=$len
|
||||
i=`expr $i + 1`
|
||||
done
|
||||
echo "Hailstone sequence from $max has $maxlen elements."
|
||||
Loading…
Add table
Add a link
Reference in a new issue