18
Weekly Challenge 119
Two quick fire tasks this week.
You are given a positive integer $N
.
Write a script to swap the two nibble of the binary representation of the given number and print the decimal number of the new binary representation. A nibble is a four-bit aggregation, or half an octet.
To keep the task simple, we only allow integer less than or equal to 255.
Rather than turning the number into a binary representation, perform some swapping and then turning it back into a decimal number, I took a more mathematical approach with binary arithmetic.
We take the first nibble and downshift it four place with $number >> 4
. We use bitwise arithmetic to get the second nibble, and multiple that by 16 to make it the first.
$ ./ch-1.pl 101
86
$ ./ch-1.pl 18
33
Write a script to generate sequence starting at 1. Consider the increasing sequence of integers which contain only 1’s, 2’s and 3’s, and do not have any doublets of 1’s like below. Please accept a positive integer $N
and print the $Nth term in the generated sequence.
1, 2, 3, 12, 13, 21, 22, 23, 31, 32, 33, 121, 122, 123, 131, …
For this task, I assign the input number as $counter
. I then have a while loop that runs while $counter != 0 and increases the number. I subtract 1 from the $counter if the number only contains 1, 2 and 3s $number =~ /^[123]*$/
and the number doesn't have double 1s index( $number, '11' ) == -1
.
$ ./ch-2.pl 5
13
$ ./ch-2.pl 10
32
$ ./ch-2.pl 60
2223
18