aboutsummaryrefslogtreecommitdiff
path: root/challenge-120/jo-37/perl
diff options
context:
space:
mode:
authorJörg Sommrey <28217714+jo-37@users.noreply.github.com>2021-07-05 14:53:16 +0200
committerJörg Sommrey <28217714+jo-37@users.noreply.github.com>2021-07-09 14:41:35 +0200
commit2b24043f65ec899e96cfa0081e2e432047bfc4e7 (patch)
treef873768d0e965b6cc0ba28a35f2fb748dee4c896 /challenge-120/jo-37/perl
parent59563d9c16649ef35dbd61cbf75f87e5507c6b20 (diff)
downloadperlweeklychallenge-club-2b24043f65ec899e96cfa0081e2e432047bfc4e7.tar.gz
perlweeklychallenge-club-2b24043f65ec899e96cfa0081e2e432047bfc4e7.tar.bz2
perlweeklychallenge-club-2b24043f65ec899e96cfa0081e2e432047bfc4e7.zip
Solution to task 1
Diffstat (limited to 'challenge-120/jo-37/perl')
-rwxr-xr-xchallenge-120/jo-37/perl/ch-1.pl67
1 files changed, 67 insertions, 0 deletions
diff --git a/challenge-120/jo-37/perl/ch-1.pl b/challenge-120/jo-37/perl/ch-1.pl
new file mode 100755
index 0000000000..ca6f560789
--- /dev/null
+++ b/challenge-120/jo-37/perl/ch-1.pl
@@ -0,0 +1,67 @@
+#!/usr/bin/perl -s
+
+use v5.16;
+use Test2::V0;
+use experimental 'signatures';
+
+our ($tests, $examples);
+
+run_tests() if $tests || $examples; # does not return
+
+die <<EOS unless @ARGV;
+usage: $0 [-examples] [-tests] [N...]
+
+-examples
+ run the examples from the challenge
+
+-tests
+ run some tests
+
+N...
+ number(s)
+
+EOS
+
+
+### Input and Output
+
+say swap_bits($_) for @ARGV;
+
+
+### Implementation
+
+sub swap_bits ($n) {
+ no warnings 'portable';
+ # Set $odd to a mask with all odd bits set in the maximum internal
+ # representation.
+ # Oops! There was a restriction to N < 256 again. Realized it only
+ # after the full-size solution had been finished.
+ state $odd = hex 5 x ((unpack '%b*', pack 'j', -1) / 4);
+
+ # Right-shift even bits and left-shift odd bits.
+ ($n & ($odd << 1)) >> 1 | ($n & $odd) << 1;
+}
+
+
+### Examples and tests
+
+sub run_tests {
+ SKIP: {
+ skip "examples" unless $examples;
+
+ is swap_bits(101), 154, 'example 1';
+ is swap_bits(18), 33, 'example 2';
+ }
+
+ SKIP: {
+ skip "tests" unless $tests;
+
+ is swap_bits(0), 0, 'no bit set';
+ is swap_bits(~0), ~0, 'all bits set';
+ is swap_bits(0x55555555), 0xaaaaaaaa, 'odd to even';
+ is swap_bits(0xaaaaaaaa), 0x55555555, 'even to odd';
+ }
+
+ done_testing;
+ exit;
+}