TWC 120: Task #1, Swap Odd/Even bits & Task #2, Clock Angle

TWC Task #1, Swap Odd/Even bits

jaredor submission for Task #1

I was just going to use a variation on last week's "Nybble Swap" task for this, but then I foolishly thought, "No, I've read Hacker's Delight I should twiddle bits!"

Okay, now that I told you about my first mistake, let me tell you, the bit twiddling was fun once it started working but I do have a little regret that it's straightforward bit-twiddling: I created a bit mask to pick out alternating bits, then just did the shifting and OR-ing you would expect to switch the even/odd bits. I can't help but wonder if there isn't some clever one-liner in Hacker's Delight. I can't claim to have remembered it even once though: I skimmed the book.

But I didn't use arrays and array indexing tricks, like I did on the nybble-swap, so I did learn something and that something is this: Once you start using bigint, you have to start thinking in a paranoid way like you do in python, "This assignment will just create a pointer, I need to make a copy." Since I'm the type who hits :w reflexively when at a lull in VIM, this isn't too outrageous for my sensibilities ... until I had to make a copy of the number 2 in a my declaration. That seemed a little much.

$ ./ --test
ok 1 - First example: 101 -> 154
ok 2 - Second example: 18 -> 33
ok 3 - Identity for numbers with 'twinned bits': 51.
ok 4 - Identity for numbers with 'twinned bits': 65535.

TWC Task #2, Clock Angle

jaredor submission for Task #2

This was just a nice, quick exercise. There was a modest boundary case to handle, changing the hour "12" to "0" internally for mathematical convenience. And there was a nice non-intuitive result that pops out in testing, that the angle for any odd minute will have a fractional remainder of half a degree.

$ ./ --test
ok 1 - First example: 03:10 is 35 degrees.
ok 2 - Second example: 04:10 is 120 degrees.
ok 3 - Twelve o'clock, the hands are coincident.
ok 4 - Six o'clock, 180 degrees.
ok 5 - One minute after six o'clock, 174.5 degrees.

Leave a comment

About Jared Martin

user-pic I blog about Perl.