Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options

binary clock from

by Skeeve (Vicar)
on Apr 03, 2013 at 23:06 UTC ( #1026914=perlmeditation: print w/replies, xml ) Need Help??

Yesterday I found this interesting code-puzzler on

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:


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

Why not give it a try!


Replies are listed 'Best First'.
Re: binary clock from
by choroba (Bishop) 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
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
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
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"

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlmeditation [id://1026914]
Approved by ww
Front-paged by ww
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2018-06-25 04:46 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (126 votes). Check out past polls.