http://www.perlmonks.org?node_id=1026914

Yesterday I found this interesting code-puzzler on java.dzone.com:

How Many 1's Appear in A Binary Clock Across an Entire Day

Say you have a binary clock, where 09:30:22 would be displayed as

Hour: 00001001
Minute: 00011110
Second: 00010110

Calculate the number of 1's that would appear over the course of an entire day of military time starting from 00:00:00 all the way up to 23:59:59

My last entry was:

while(1){$_+=(unpack"%32B*",pack"i3",gmtime++$i)||last}print

I'm sure it's possible to shorten that.

Why not give it a try!


s$$([},&%#}/&/]+}%&{})*;#$&&s&&$^X.($'^"%]=\&(|?*{%
+.+=%;.#_}\&"^"-+%*).}%:##%}={~=~:.")&e&&s""`$''`"e

Replies are listed 'Best First'.
Re: binary clock from java.dzone.com
by choroba (Cardinal) on Apr 04, 2013 at 07:43 UTC
    Golf? Without really changing the logic, just using shorter notation:
    # 1 2 3 4 5 #12345678901234567890123456789012345678901234567890123456789 $_+=(unpack"%32B*",pack"i3",gmtime++$i)||$x++until$x;print
    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: binary clock from java.dzone.com
by hdb (Monsignor) on Apr 04, 2013 at 09:44 UTC

    Explicit loop and abusing $\ saves a few characters:

    # 1 2 3 4 5 #12345678901234567890123456789012345678901234567890123456789 $\+=unpack("%32B*",pack"i3",gmtime$_)for(1..86400);print
      Parens could be ommited twice:
      # 1 2 3 4 5 #12345678901234567890123456789012345678901234567890123456789 $\+=unpack"%32B*",pack"i3",gmtime$_ for 1..86400;print
      My shortest approach:
      # 1 #123456789012345 print 682560
        which can be further shortened by using perl -d. Also, this version doesn't entail knowing the answer in advance:
        # 24*2*60*(64*3-20)+60*60*(8*2+4*3*3) # =2880*(4*43+5*13) # =2880*237 # 1 2 3 #123456789012345678901234567890123456789 p 8640*79
Re: binary clock from java.dzone.com
by Loops (Curate) on Apr 04, 2013 at 08:56 UTC
    Hey Skeeve,

    Fun one, don't think there will be much improvement to be found on your entry. Just a minor tweak to it below

    $_+=$a while($a=unpack"%32B*",pack"i3",gmtime++$i);print
    update Sorry for last effort... updated with new try of same size...
      Returns 0 for me on Perl 5.16.0.
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
        Me too... Some sort of weird sleep deprivation blindness. This is how programmers blow up rocketships. Taking myself out of the game til tomorrow... Peace.
Re: binary clock from java.dzone.com
by Anonymous Monk on Apr 04, 2013 at 11:21 UTC
    Nothing to be crowing about .. the essential trick is explicitly pointed-out in "perldoc -f unpack"