‹ BackHN Continuity

Thread

Small programming tricks

681 points · 294 comments · signa11

  1. butterNaN · · focus · HN ↗
    In case you were confused about the logarithm trick, here's what I think it's trying to say.

    This hypothetical system has a bunch of users, belonging to groups. A possibility is that most groups have a only handful of users, but a few famous group might have disproportionate amount of users say 500,000.

    If you wanted to put these groups in buckets, you can create linear buckets of fixed size based on number of users like

        bucket 1: 0 to 100 users
        bucket 2: 101 to 200 users
        bucket 3: 201 to 300 users
        ...
        bucket 600000: 599001 to 600000 users
    
    Now the problem is you have way too many buckets, and most of them are probably empty. In situations these "buckets" actually cost you money, you might want to optimise the number of buckets.

    So the code converts the user distribution to logarithmic scale:

        const bucket = Math.floor(Math.log10(userInGroupCount))
    
    This essentially creates buckets as number of digits:

       bucket 1: 0 to 9 users
       bucket 2: 10 to 99 users
       bucket 3: 100 to 999 users
       bucket 4: 1000 to 9999 users
       bucket 5: 10000 to 99999 users
       bucket 6: 100000 to 999999 users
    
    With this, you have needed only 6 buckets. Moreover, this probably maps to the real life distribution, so your charts read cleanly.
    1. butterNaN · · focus · HN ↗
      (you'll have to handle the case where `userInGroupCount == 0` in the code given)
Open on Hacker News to reply ↗

Unofficial Hacker News client; not affiliated with Y Combinator.