Your skill will accomplish what the force of many cannot |
|
PerlMonks |
mini-golf: convert integer into list of powers of twoby xyzzy (Pilgrim) |
on May 23, 2012 at 20:24 UTC ( [id://972098]=perlmeditation: print w/replies, xml ) | Need Help?? |
I want(ed) to write a function that would expand a bit field (unsigned integer) into a list of powers of two, so f(0) = (), f(4) = (4), f(13) = (1,4,8), f(31) = (1,2,4,8,16)... I thought storing options in a single field and then having a separate table for definitions was a good idea. I have since realized that I should use object-oriented relational databases the way they are designed to be used, but I still think it's an interesting exerc ise. Anyway, I came up with a 5-minute-one-liner solution and was going to post a SoPW, but after I realized I wasn't going to use it anyway and since it was a one-liner I decided to turn it into a golf meditation. I'm a pretty lousy golfer and I never came up with challenges before but I'm curious how short someone else can make this. I originally wrote it as an anonymous function, so a valid solution should start with sub{ and end with } and return a list. My original 5-minute solution
After I decided to golf it, I got rid of $m and figured out that iterating $n = 0,1,2,... instead of $n = 1,2,4,8... would shave off three chars for an even 70
$,=qq.\n.;print q.\/\/____\/.,q./\ \ / / \\.,q. /_/__.,q.. Happy, sober, smart: pick two.
Back to
Meditations
|
|