langs a-z

This commit is contained in:
Ingy döt Net 2013-04-10 22:43:41 -07:00
parent db842d013d
commit d066446780
11389 changed files with 98361 additions and 1020 deletions

View 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}"

View 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."

View file

@ -0,0 +1,51 @@
# Outputs a hailstone sequence from !:1, with one element per line.
# Clobbers $n.
alias hailstone eval \''@ n = \!:1:q \\
echo $n \\
while ( $n != 1 ) \\
if ( $n % 2 ) then \\
@ n = 3 * $n + 1 \\
else \\
@ n /= 2 \\
endif \\
echo $n \\
end \\
'\'
set sequence=(`hailstone 27`)
echo "Hailstone sequence from 27 has $#sequence elements:"
@ i = $#sequence - 3
echo " $sequence[1-4] ... $sequence[$i-]"
# hailstone-length $i
# acts like
# @ len = `hailstone $i | wc -l | tr -d ' '`
# but without forking any subshells.
alias hailstone-length eval \''@ n = \!:1:q \\
@ len = 1 \\
while ( $n != 1 ) \\
if ( $n % 2 ) then \\
@ n = 3 * $n + 1 \\
else \\
@ n /= 2 \\
endif \\
@ len += 1 \\
end \\
'\'
@ i = 1
@ max = 0
@ maxlen = 0
while ($i < 100000)
# XXX - I must run hailstone-length in a subshell, because my
# C Shell has a bug when it runs hailstone-length inside this
# while ($i < 1000) loop: it forgets about this loop, and
# reports an error <<end: Not in while/foreach.>>
@ len = `hailstone-length $i; echo $len`
if ($len > $maxlen) then
@ max = $i
@ maxlen = $len
endif
@ i += 1
end
echo "Hailstone sequence from $max has $maxlen elements."