Enigmatic Code

Programming Enigma Puzzles

Enigma 1645: Neighbourhood watch

From New Scientist #2811, 7th May 2011 [link]

In my street the odd-numbered houses are on the left and the even-numbered houses are on the right. The first house on the left, number 1, is immediately opposite number 2, then number 3 is opposite number 4, and so on. Each house has its number on the gate.

On a recent walk I started at house number 1 and walked up the left-hand side of the road to the very end, then I crossed to the house opposite and walked back down the right-hand side until I reached my own house.

I counted the number of occurrences of the digit 1 that I had seen on the gates, and the number of occurrences of the digit 2: after entering my own gate the product of these two totals was a two-figure number.

Had I stopped counting at the house opposite my own, then the product would have been smaller; in fact it would have been the reverse of the eventual product.

What is my house number?

[enigma1645]

Advertisements

One response to “Enigma 1645: Neighbourhood watch

  1. jimrandell 7 December 2011 at 2:44 pm

    The following Python code runs in 32ms.

    from itertools import count
    from enigma import irange, printf
    
    def solve():
      for n in count(0):
        N = 2 * n + 1
        (ones, twos) = (0, 0)
        ps = {}
        # go up the left side
        for l in irange(1, N, step=2):
          s = str(l)
          ones += s.count('1')
          twos += s.count('2')
          ps[l] = ones * twos
          if not(ps[l] < 100): return
        # and down the right
        for r in irange(N + 1, 1, step=-2):
          s = str(r)
          ones += s.count('1')
          twos += s.count('2')
    
          p = ones * twos
          po = ps[r-1]
          if 9 < p < 100 and po < p and str(po) == str(p)[::-1]:
            printf("N={N} r={r} p[{r}]={p} p[{r1}]={po}", r1=r-1)
    
    solve()
    

    Solution: Your house number is 32.

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: