diff options
Diffstat (limited to 'challenge-079/abigail/awk')
| -rw-r--r-- | challenge-079/abigail/awk/ch-1.awk | 33 | ||||
| -rw-r--r-- | challenge-079/abigail/awk/ch-2.awk | 60 |
2 files changed, 93 insertions, 0 deletions
diff --git a/challenge-079/abigail/awk/ch-1.awk b/challenge-079/abigail/awk/ch-1.awk new file mode 100644 index 0000000000..56abe1a74d --- /dev/null +++ b/challenge-079/abigail/awk/ch-1.awk @@ -0,0 +1,33 @@ +# +# Challenge: +# +# You are given a positive number $N. +# +# Write a script to count the total numbrer of set bits of the binary +# representations of all numbers from 1 to $N and return +# $total_count_set_bit % 1000000007. +# +# https://perlweeklychallenge.org/blog/perl-weekly-challenge-079/ +# + +# +# This is A000778 (https://oeis.org/A000788). There's a recursive formala +# for the number of bits in the binary representation of 0 .. $N: +# +# bits (0) = 0 +# bits (2 * N) = bits (N) + bits (N - 1) + N +# bits (2 * N + 1) = 2 * bits (N) + N + 1 +# + +function f(nn, n) { + if (nn == 0) {return (0);} + if (nn % 2 == 1) { + n = (nn - 1) / 2; + return 2 * f(n) + n + 1; + } + n = nn / 2; + return f(n) + f(n - 1) + n; +} + +BEGIN {bignum = 1000000007;} + {print f($1) % bignum;} diff --git a/challenge-079/abigail/awk/ch-2.awk b/challenge-079/abigail/awk/ch-2.awk new file mode 100644 index 0000000000..164dc88b6f --- /dev/null +++ b/challenge-079/abigail/awk/ch-2.awk @@ -0,0 +1,60 @@ +# +# Challenge: +# +# You are given an array of positive numbers @N. +# Write a script to represent it as Histogram Chart and find out +# how much water it can trap. +# + +{ + # + # First, find the maximum value. + # + max = 0; + for (i = 1; i <= NF; i ++) { + if ($i > max) { + max = $i; + } + } + + # + # Given the value, we know how wide every column must be. + # + format = "%" length (max) "s"; + show = sprintf (" " format, "#"); + noshow = sprintf (" " format, " "); + + # + # Print the histogram + # + for (vol = max; vol; vol --) { + printf format, vol; + for (i = 1; i <= NF; i ++) { + if ($i >= vol) {printf show;} + else {printf noshow;} + } + printf "\n"; + } + + # + # Print the line with the bars. + # + bar = ""; + for (i = 0; i < length (max); i ++) { + bar = bar "_"; + } + printf bar; + for (i = 1; i <= NF; i ++) { + printf " " bar; + } + printf "\n"; + + # + # Print the line with the totals + # + printf format, " "; + for (i = 1; i <= NF; i ++) { + printf " " format, $i; + } + printf "\n"; +} |
