DEV Community

Simon Green
Simon Green

Posted on

Weekly Challenge 119

Challenge, My solutions

Two quick fire tasks this week.

TASK #1 › Swap Nibbles

Task

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.

My solution

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.

Examples

$ ./ch-1.pl 101
86

$ ./ch-1.pl 18
33
Enter fullscreen mode Exit fullscreen mode

TASK #2 › Sequence without 1-on-1

Task

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, …

My solution

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.

Examples

$ ./ch-2.pl 5
13

$ ./ch-2.pl 10
32

$ ./ch-2.pl 60
2223
Enter fullscreen mode Exit fullscreen mode

Top comments (0)