aboutsummaryrefslogtreecommitdiff
path: root/challenge-271/sgreen/perl/ch-2.pl
diff options
context:
space:
mode:
authorSimon Green <mail@simon.green>2024-06-02 16:44:05 +1000
committerSimon Green <mail@simon.green>2024-06-02 16:44:05 +1000
commit9570cd789d0f24fcfba65675b371c5feae0e3dc8 (patch)
tree5c3aea0411b8c26b5c9c1e000decba498789a4ed /challenge-271/sgreen/perl/ch-2.pl
parent5ea56aa37a9f0b7098302e2acb76c73907c70bde (diff)
downloadperlweeklychallenge-club-9570cd789d0f24fcfba65675b371c5feae0e3dc8.tar.gz
perlweeklychallenge-club-9570cd789d0f24fcfba65675b371c5feae0e3dc8.tar.bz2
perlweeklychallenge-club-9570cd789d0f24fcfba65675b371c5feae0e3dc8.zip
sgreen solutions to challenge 271
Diffstat (limited to 'challenge-271/sgreen/perl/ch-2.pl')
-rwxr-xr-xchallenge-271/sgreen/perl/ch-2.pl21
1 files changed, 21 insertions, 0 deletions
diff --git a/challenge-271/sgreen/perl/ch-2.pl b/challenge-271/sgreen/perl/ch-2.pl
new file mode 100755
index 0000000000..170d3c7e9b
--- /dev/null
+++ b/challenge-271/sgreen/perl/ch-2.pl
@@ -0,0 +1,21 @@
+#!/usr/bin/env perl
+
+use strict;
+use warnings;
+use feature 'say';
+use experimental 'signatures';
+
+sub one_bits($int) {
+ # Convert the integer to binary, and count the number of 1s
+ my $bin = sprintf( "%b", $int );
+ return ($bin =~ tr/1/1/);
+}
+
+sub sort_by_1_bits (@ints) {
+ # Sort the integers by the number of 1 bits, and by the integer value if
+ # the number of 1 bits is the same
+ my @sorted = sort { one_bits($a) <=> one_bits($b) || $a <=> $b } @ints;
+ say '(' . join( ', ', @sorted ) . ')';
+}
+
+sort_by_1_bits(@ARGV); \ No newline at end of file