Recent Updates Page 49 Toggle Comment Threads | Keyboard Shortcuts

  • Unknown's avatar

    Jim Randell 9:58 am on 13 October 2020 Permalink | Reply
    Tags:   

    Teaser 1915: Rabbit, rabbit, rabbit, … 

    From The Sunday Times, 30th May 1999 [link]

    In each of the four houses in a small terrace lives a family with a boy, a girl and a pet rabbit. One of the children has just mastered alphabetical order and has listed them thus:

    I happen to know that this listing gave exactly one girl, one boy and one rabbit at her, his or its correct address. I also have the following correct information: neither Harry nor Brian lives at number 3, and neither Donna nor Jumper lives at number 1. Gail’s house number is one less than Mopsy’s house number, and Brian’s house number is one less than Cottontail’s.

    Who lives where?

    This puzzle is included in the book Brainteasers (2002). The puzzle text above is taken from the book.

    [teaser1915]

     
    • Jim Randell's avatar

      Jim Randell 9:58 am on 13 October 2020 Permalink | Reply

      See also: Teaser 2944.

      This Python program runs in 44ms.

      Run: [ @repl.it ]

      from enigma import subsets, printf
      
      # the names
      girls = "ADGK"
      boys = "BEHL"
      rabbits = "CFJM"
      
      # choose an ordering where exactly k of the original ordering is correct
      def choose(xs, k=1):
        for ys in subsets(xs, size=len, select="P"):
          if sum(x == y for (x, y) in zip(xs, ys)) == k:
            yield ys
      
      # choose an ordering for the boys
      for boy in choose(boys):
        # "neither H nor B live at number 3 [= index 2]"
        if boy[2] == 'H' or boy[2] == 'B': continue
      
        # choose an ordering for the rabbits
        for rabbit in choose(rabbits):
          # "J does not live at number 1 [=index 0]"
          if rabbit[0] == 'J': continue
          # "B's number is one less than C's"
          if boy.index('B') + 1 != rabbit.index('C'): continue
      
          # choose an ordering for the girls
          for girl in choose(girls):
            # "D does not live at number 1 [= index 0]"
            if girl[0] == 'D': continue
            # "G's number is one less than M's"
            if girl.index('G') + 1 != rabbit.index('M'): continue
      
            # output solution
            for (n, (g, b, r)) in enumerate(zip(girl, boy, rabbit), start=1):
              printf("{n}: {g} {b} {r}")
            printf()
      

      Solution: The occupants of each house are:

      1: Kelly, Harry, Flopsy
      2: Alice, Brian, Jumper
      3: Gail, Eric, Cottontail
      4: Donna, Laurie, Mopsy

      Like

    • Frits's avatar

      Frits 4:56 pm on 13 October 2020 Permalink | Reply

      from enigma import SubstitutedExpression
      
      girls   = ("", "Alice", "Donna", "Gail", "Kelly")
      boys    = ("", "Brian", "Eric", "Harry", "Laurie")
      rabbits = ("", "Cottontail", "Flopsy", "Jumper", "Mopsy")
      
      # the alphametic puzzle
      p = SubstitutedExpression(
        [
         # "B's number is one less than C's"
         "B + 1 = C",
         # "G's number is one less than M's" 
         "G + 1 = M",
         # listing gave exactly one girl, one boy and one rabbit at
         # her, his or its correct address
         "sum((A == 1, D == 2, G == 3, K == 4)) == 1",
         "sum((B == 1, E == 2, H == 3, L == 4)) == 1",
         "sum((C == 1, F == 2, J == 3, M == 4)) == 1",
        ],
        answer="ADGK, BEHL, CFJM",   
        digits=range(1,5),
        distinct=('ADGK', 'BEHL', 'CFJM'),
        # "D does not live at number 1"
        # "J does not live at number 1"
        # "neither H nor B live at number 3"
        d2i={1 : "CMDJ", 3 : "BH", 4 : "BG"}, 
        verbose=0,
        #reorder=0,
      )
      
      # Print answers
      for (_, ans) in p.solve(): 
        for k in "1234":
          x = [j+1 for x in ans for j, y in enumerate(str(x)) if y == k]
          print(f"house {k}: {girls[x[0]]:<6} {boys[x[1]]:<7} {rabbits[x[2]]}")
        
      # house 1: Kelly  Harry   Flopsy
      # house 2: Alice  Brian   Jumper
      # house 3: Gail   Eric    Cottontail
      # house 4: Donna  Laurie  Mopsy
      

      Like

    • John Crabtree's avatar

      John Crabtree 6:34 pm on 13 October 2020 Permalink | Reply

      Flopsy must be at #1.
      Brian cannot be at #2, otherwise Jumper and Mopsy are both correct or both incorrect.
      And so Brian is at #1, Cottontail at #3, Jumper at #1, Mopsy at #4, and Gail at #3, etc

      Like

  • Unknown's avatar

    Jim Randell 12:03 pm on 11 October 2020 Permalink | Reply
    Tags: by: J. V. Sharp   

    Brain-Teaser 10: [Clock sync] 

    From The Sunday Times, 30th April 1961 [link]

    David’s train left at 11 am. The previous night David had set his bedroom clock and watch in such a way that they would read the correct time when he intended to leave the following morning. His clock lost regularly, while his watch gained regularly. The next morning he actually left when the clock said 8:15 and his watch said 8:10. When the train left the station (on time) David looked at his watch and noticed that it said 11:10. David had planned to leave at an exact number of minutes past 8 and he worked out afterwards that he had left at an exact number of minutes past 8.

    At what time did David intend to leave, and at what time did he actually leave?

    This puzzle was originally published with no title.

    [teaser10]

     
    • Jim Randell's avatar

      Jim Randell 12:04 pm on 11 October 2020 Permalink | Reply

      Let’s suppose David intended to leave at m minutes past 8:00am (so m = 0 .. 59).

      At this time both the clock (which runs slow) and the watch (which runs fast) would both say the correct time:

      clock(m) = m
      watch(m) = m

      If the watch runs at a rate of w (> 1), and the clock at a rate of c (< 1) we have:

      clock(t) = m + (t − m)c
      watch(t) = m + (t − m)w

      Now, he actually left at n minutes past 8:00am (so n = 0 .. (m − 1)).

      And at this time the clock read 8:15 and the watch read 8:10:

      clock(n) = 15
      watch(n) = 10

      (The fact the clock is ahead of the watch tells us that the actual time is earlier than the intended time).

      So:

      m + (n − m)c = 15 ⇒ c = (m − 15) / (m − n)
      m + (n − m)w = 10 ⇒ w = (m − 10) / (m − n)

      And at the moment the train left (11:00am) the watch read 11:10:

      watch(180) = 190
      m + (180 − m)w = 190
      (180 − m)(m − 10) = (190 − m)(m − n)
      n = 1800 / (190 − m)
      m = 190 − 1800 / n

      And we need c < 1 and w > 1:

      m − 15 < m − n
      m − 10 > m − n
      10 < n < 15

      So there are only 4 values to check, which we can do manually or with a program.

      from enigma import (irange, div, printf)
      
      # choose a value for n (actual leave time)
      for n in irange(11, 14):
        # calculate m (intended leave time)
        m = div(190 * n - 1800, n)
        if m is None: continue
        printf("n={n} -> m={m}")
      

      Solution: David intended to leave at 8:40am. He actually left at 8:12am.

      The watch runs at a rate of 15/14 (approx. 107%). So it gains 2 minutes every 28 minutes.

      The clock runs at a rate of 25/28 (approx. 89%). So it loses 3 minutes every 28 minutes.

      Like

    • John Crabtree's avatar

      John Crabtree 6:38 pm on 13 October 2020 Permalink | Reply

      If not leaving at the intended time, Dave’s actual time of departure must be between those indicated on the clock and watch. Assume that he left x minutes after 8:10 where x = 1, 2, 3 or 4.
      The watch would be correct (170 – x) * x / (x + 10) = … = 180 – x – 1800 / (x + 10) minutes later, which is an integer.
      And so x = 2, and the solution follows.

      Like

  • Unknown's avatar

    Jim Randell 4:38 pm on 9 October 2020 Permalink | Reply
    Tags:   

    Teaser 3029: Square jigsaws 

    From The Sunday Times, 11th October 2020 [link] [link]

    I chose a whole number and asked my grandson to cut out all possible rectangles with sides a whole number of centimetres whose area, in square centimetres, did not exceed my number. (So, for example, had my number been 6 he would have cut out rectangles of sizes 1×1, 1×2, 1×3, 1×4, 1×5, 1×6, 2×2 and 2×3). The total area of all the pieces was a three-figure number of square centimetres.

    He then used all the pieces to make, in jigsaw fashion, a set of squares. There were more than two squares and at least two pieces in each square.

    What number did I originally choose?

    [teaser3029]

     
    • Jim Randell's avatar

      Jim Randell 5:17 pm on 9 October 2020 Permalink | Reply

      (See also: Enigma 1251, Enigma 1491).

      If the squares are composed of at least two pieces, they must be at least 3×3.

      This Python program works out the only possible original number that can work, but it doesn’t demonstrate the the rectangles can be assembled into the required squares.

      It runs in 44ms.

      Run: [ @repl.it ]

      from enigma import irange, inf, printf
      
      # generate rectangles with area less than n
      def rectangles(n):
        for i in irange(1, n):
          if i * i > n: break
          for j in irange(i, n // i):
            yield (i, j)
      
      # decompose t into squares
      def decompose(t, m=1, ss=[]):
        if t == 0:
          yield ss
        else:
          for k in irange(m, t):
            s = k * k
            if s > t: break
            yield from decompose(t - s, k, ss + [k])
      
      # make squares from the rectangular pieces, with total area A
      def fit(rs, A):
        # determine the maximum dimension of the rectangles
        m = max(j for (i, j) in rs)
        for n in irange(m, A):
          if n * n > A: break
          # decompose the remaining area into squares
          for ss in decompose(A - n * n, 3):
            if len(ss) < 2: continue
            yield ss + [n]
      
      # consider the chosen number
      for n in irange(2, inf):
        # collect the rectangles and total area
        rs = list(rectangles(n))
        A = sum(i * j for (i, j) in rs)
        if A < 100: continue
        if A > 999: break
      
        # fit the rectangles in a set of squares
        for ss in fit(rs, A):
          printf("n={n}, A={A} -> ss={ss}")
      

      Solution: The original number was 29.

      The rectangles cut out are:

      1, 2, 3, …, 29
      2, 3, …, 14
      3, …, 9
      4, 5, 6, 7
      5

      With a total area of 882 cm².

      The 1×29 piece must fit into a square of size 29×29 or larger, but this is the largest square we can make, so there must be a 29×29 square, which leaves an area of 41 cm². This can be split into squares as follows:

      41 = 3² + 4² + 4²
      41 = 4² + 5²

      It turns out that it only possible to construct a packing using the second of these.

      I used the polyominoes.py library that I wrote for Teaser 2996 to assemble the rectangles into a viable arrangement of squares. It runs in 19 minutes. (The adapted program is here).

      Here is a diagram showing one way to pack the rectangles into a 4×4, 5×5 and a 29×29 square:

      Like

      • Frits's avatar

        Frits 2:27 pm on 10 October 2020 Permalink | Reply

        @Jim,

        Wouldn’t it be easier to use the chosen number n as maximum dimension (line 23)?

        Like

        • Jim Randell's avatar

          Jim Randell 11:51 am on 11 October 2020 Permalink | Reply

          @Frits: Probably. When I started writing the program I was thinking about a constructive solution, that would produce a packing of the rectangles into the required squares. This is a cut-down version of the program which finds possible sets of squares to investigate – fortunately the solutions found all correspond to the same original number, so if there is an answer we know what it must be.

          And it turns out that we don’t need to examine the set of rectangles to determine the maximum dimension, so we could just pass it in. In fact we don’t need to collect the rectangles at all. Here’s a better version of the cut-down program:

          from enigma import (irange, inf, divisors_pairs, printf)
          
          # decompose t into squares
          def decompose(t, m=1, ss=[]):
            if t == 0:
              yield ss
            else:
              for k in irange(m, t):
                s = k * k
                if s > t: break
                yield from decompose(t - s, k, ss + [k])
          
          # find at least 3 potential squares with total area A
          # that can accomodate a rectangle with max dimension m
          def fit(A, m):
            for n in irange(m, A):
              a = A - n * n
              if a < 18: break
              # decompose the remaining area into at least 2 squares
              # with minimum dimension 3
              for ss in decompose(a, 3):
                if len(ss) > 1:
                  yield ss + [n]
          
          # collect rectangles with increasing area
          A = 0
          for n in irange(1, inf):
            # add in rectangles of area n
            A += sum(i * j for (i, j) in divisors_pairs(n))
          
            # look for 3-digit total area
            if A < 100: continue
            if A > 999: break
          
            # find a set of squares with the same area
            for ss in fit(A, n):
              printf("n={n} A={A} -> ss={ss}")
          

          I did complete a program that finds a viable packing, but it takes a while to run (19 minutes).

          I’ll post the diagram with the answer later.

          Like

          • Frits's avatar

            Frits 5:59 pm on 11 October 2020 Permalink | Reply

            @Jim, a nice solution with the divisor pairs.
            I think we can only form one 3×3 square at most (out of 3 possibilities).

            Like

    • Frits's avatar

      Frits 1:29 pm on 10 October 2020 Permalink | Reply

      I did a manual check to see if the reported squares can be formed in 2-D with the rectangular pieces.

       
      # select numbers from list <li> so that sum of numbers equals <n>
      def decompose(n, li, sel=[]):
        if n == 0:
          yield sel
        else:
          for i in {j for j in range(len(li)) if li[j] <= n}:
            yield from decompose(n - li[i], li[i:], sel + [li[i]])     
              
      # squares under 1000, square 2x2 can't be formed from rectangles                 
      squares = [n*n for n in range(3, 32)]
      
      rectangles = lambda n: [(i, j) for i in range(1, n + 1) 
                              for j in range(i, n + 1) if i * j <= n]
      
      area = lambda li: sum(i * j for (i, j) in li)
      
      # candidates with three-figure number area; area must be
      # at least largest square (i*i) plus the 2 smallest squares 9 and 16
      cands = lambda: {i: area(rectangles(i)) for i in range(7, 32) 
                       if area(rectangles(i)) in range(100, 1000) and
                          area(rectangles(i)) >= i * i + 25}
      
      # check if solution exist for candidates
      for (n, a) in cands().items(): 
        # biggest square should be at least n x n due to 1 x n piece
        for big in range(n, 32):
          # list of squares to consider (excluding the biggest square)
          sq = [x for x in squares if x <= a - (big * big) - 9]
          # select squares which together with biggest square will sum to area <a>
          for s in decompose(a - (big * big), sq):
            if len(s) > 1:
              print(f"number chosen = {n}, area={a}, squares={s + [big * big]}")
      

      Like

  • Unknown's avatar

    Jim Randell 10:36 am on 8 October 2020 Permalink | Reply
    Tags:   

    Teaser 1908: Dunroamin 

    From The Sunday Times, 11th April 1999 [link]

    At our DIY store you can buy plastic letters of the alphabet in order to spell out your house name. Although all the A’s cost the same as each other, and all the B’s cost the same as each other, etc., different letters sometimes cost different amounts with a surprisingly wide range of prices.

    I wanted to spell out my house number:

    FOUR

    and the letters cost me a total of £4. Surprised by this coincidence I worked out the cost of spelling out each of the numbers from ONE to TWELVE. In ten out of the twelve cases the cost in pounds equalled the number being spelt out.

    For which house numbers was the cost different from the number?

    This puzzle is included in the book Brainteasers (2002). The puzzle text above is taken from the book.

    [teaser1908]

     
    • Jim Randell's avatar

      Jim Randell 10:37 am on 8 October 2020 Permalink | Reply

      (See also: Teaser 2756, Enigma 1602).

      This Python program checks to see if each symbol can be assigned a value that is a multiple of 25p to make the required 10 words correct (and also checks that the remaining two words are wrong).

      Instead of treating the letters G, H, R, U separately, we treat them as GH, HR, UR, which reduces the number of symbols to consider by 1.

      The program runs in 413ms.

      Run: [ @repl.it ]

      from enigma import (irange, subsets, update, unpack, diff, join, map2str, printf)
      
      # <value> -> <symbol> mapping
      words = {
        100: ("O", "N", "E"),
        200: ("T", "W", "O"),
        300: ("T", "HR", "E", "E"),
        400: ("F", "O", "UR"),
        500: ("F", "I", "V", "E"),
        600: ("S", "I", "X"),
        700: ("S", "E", "V", "E", "N"),
        800: ("E", "I", "GH", "T"),
        900: ("N", "I", "N", "E"),
        1000: ("T", "E", "N"),
        1100: ("E", "L", "E", "V", "E" ,"N"),
        1200: ("T" ,"W", "E", "L", "V", "E"),
      }
      
      # decompose t into k numbers, in increments of step
      def decompose(t, k, step, ns=[]):
        if k == 1:
          yield ns + [t]
        elif k > 1:
          k_ = k - 1
          for n in irange(step, t - k_ * step, step=step):
            yield from decompose(t - n, k_, step, ns + [n])
      
      # find undefined symbols and remaining cost
      def remaining(v, d):
        (us, t) = (set(), v)
        for x in words[v]:
          try:
            t -= d[x]
          except KeyError:
            us.add(x)
        return (us, t)
      
      # find values for vs, with increments of step
      def solve(vs, step, d=dict()):
        # for each value find remaining cost and undefined symbols
        rs = list()
        for v in vs:
          (us, t) = remaining(v, d)
          if t < 0 or bool(us) == (t == 0): return
          if t > 0: rs.append((us, t, v))
        # are we done?
        if not rs:
          yield d
        else:
          # find the value with the fewest remaining symbols (and lowest remaining value)
          (us, t, v) = min(rs, key=unpack(lambda us, t, v: (len(us), t)))
          # the remaining values
          vs = list(x for (_, _, x) in rs if x != v)
          # allocate the unused symbols
          us = list(us)
          for ns in decompose(t, len(us), step):
            # solve for the remaining values
            yield from solve(vs, step, update(d, us, ns))
      
      # choose the 2 equations that are wrong
      for xs in subsets(sorted(words.keys()), size=2):
        # can't include FOUR
        if 400 in xs: continue
        # find an allocation of values
        for d in solve(diff(words.keys(), xs), 25):
          xvs = list(sum(d[s] for s in words[x]) for x in xs)
          if all(x != v for (x, v) in zip(xs, xvs)):
            # output solution
            wxs = list(join(words[x]) for x in xs)
            printf("wrong = {wxs}", wxs=join(wxs, sep=", ", enc="[]"))
            printf("-> {d}", d=map2str(d, sep=" ", enc=""))
            for (x, xv) in zip(wxs, xvs):
              printf("  {x} = {xv}p")
            printf()
            break
      

      Solution: NINE and TEN do not cost an amount equal to their number.

      One way to allocate the letters, so that ONEEIGHT, ELEVEN, TWELVE work is:

      25p = F, H, N, O, T
      50p = E, X
      150p = W, R
      200p = I, U
      225p = V
      350p = S
      500p = G
      700p = L

      (In this scheme: NINE costs £3 and TEN costs £1).

      But there are many other possible assignments.

      You can specify smaller divisions of £1 for the values of the individual symbols, but the program takes longer to run.

      It makes sense that NINE and TEN don’t cost their value, as they are short words composed entirely of letters that are available in words that cost a lot less.


      Here’s a manual solution:

      We note that ONE + TWELVE use the same letters as TWO + ELEVEN, so if any three of them are correct so is the fourth. So there must be 0 or 2 of the incorrect numbers among these four.

      Now, if ONE and TEN are both correct, then any number with value 9 or less with a T in it must be wrong. i.e. TWO, THREE, EIGHT. Otherwise we could make TEN for £10 or less, and have some letters left over. And this is not possible.

      If ONE is incorrect, then the other incorrect number must be one of TWO, ELEVEN, TWELVE, and all the remaining numbers must be correct. So we could buy THREE and SEVEN for £10, and have the letters to make TEN, with EEEHRSV left over. This is not possible.

      So ONE must be correct, and TEN must be one of the incorrect numbers.

      Now, if NINE is correct, then any number with value 7 or less with an I in it must be incorrect. Which would mean FIVE and SIX are incorrect. This is not possible.

      Hence, the incorrect numbers must be NINE and TEN.

      All that remains is to demonstrate one possible assignment of letters to values where NINE and TEN are incorrect and the rest are correct. And the one found by the program above will do.

      Like

    • GeoffR's avatar

      GeoffR 6:36 pm on 8 October 2020 Permalink | Reply

      I used a wide range of upper .. lower bound values for letter variables.

      The programme would not run satisfactorily under the Geocode Solver, but produced a reasonable run time under the Chuffed Solver. It confirmed the incorrect numbers were NINE and TEN.

      % A Solution in MiniZinc
      include "globals.mzn";
       
      var 10..900:O; var 10..900:N; var 10..900:E; var 10..900:T;
      var 10..900:W; var 10..900:H; var 10..900:R; var 10..900:F;
      var 10..900:U; var 10..900:V; var 10..900:I; var 10..900:L;
      var 10..900:G; var 10..900:S; var 10..900:X;
      
      constraint sum([
      O+N+E == 100, T+W+O == 200, T+H+R+E+E == 300, F+O+U+R == 400,
      F+I+V+E == 500, S+I+X == 600, S+E+V+E+N == 700,
      E+I+G+H+T == 800, N+I+N+E == 900, T+E+N == 1000,
      E+L+E+V+E+N == 1100, T+W+E+L+V+E == 1200]) == 10;
      
      solve satisfy;
      
      output [" ONE = " ++ show (O + N + E) ++
      "\n TWO = " ++ show (T + W + O ) ++
      "\n THREE = " ++ show (T + H + R + E + E) ++
      "\n FOUR = " ++ show (F + O + U + R) ++
      "\n FIVE = " ++ show (F + I + V + E) ++
      "\n SIX = " ++ show (S + I + X) ++
      "\n SEVEN = " ++  show (S + E + V + E + N) ++
      "\n EIGHT = " ++ show (E + I + G + H + T) ++
      "\n NINE = " ++ show (N + I + N + E) ++
      "\n TEN = " ++ show (T + E + N) ++
      "\n ELEVEN = " ++ show (E + L + E + V + E + N) ++
      "\n TWELVE = " ++ show (T + W + E + L + V + E) ++
      "\n\n [O N E T W H R F U V I L G S X = ]" ++ 
      show([O, N, E, T, W, H, R, F, U, V, I, L, G, S, X]) ];
      
      %  ONE = 100
      %  TWO = 200
      %  THREE = 300
      %  FOUR = 400
      %  FIVE = 500
      %  SIX = 600
      %  SEVEN = 700
      %  EIGHT = 800
      %  NINE = 171   << INCORRECT
      %  TEN = 101    << INCORRECT
      %  ELEVEN = 1100
      %  TWELVE = 1200
      %  Letter Values (One of many solutions)
      %  [O    N   E   T   W    H   R    F   U    V    I   L    G    S    X = ]
      %  [10, 71, 19, 11, 179, 13, 238, 10, 142, 461, 10, 511, 747, 130, 460]
      %  time elapsed: 0.04 s
      % ----------
      
      
      
      

      Like

      • Frits's avatar

        Frits 7:47 pm on 11 October 2020 Permalink | Reply

        @GeoffR, As Jim pointed out to me (thanks) that FOUR can not be an incorrect number your MiniZinc program can be adapted accordingly. Now both run modes have similar performance.

        Like

    • Frits's avatar

      Frits 4:56 pm on 11 October 2020 Permalink | Reply

      Pretty slow (especially for high maximum prizes).

      I combined multiple “for loops” into one loop with the itertools product function so it runs both under Python and PyPy.

      @ Jim, your code has some unexplained “# can’t include FOUR” code (line 62, 63).
      It is not needed for performance.

       
      from enigma import SubstitutedExpression
      from itertools import product
      
      mi = 25      # minimum prize
      step = 25    # prizes differ at least <step> pennies 
      ma = 551     # maximum prize + 1
      bits = set() # x1...x12 are bits, 10 of them must be 1, two them must be 0
      
      # return numbers in range and bit value 
      # (not more than 2 bits in (<li> plus new bit) may be 0)
      rng = lambda m, li: product(range(mi, m, step), 
                                 (z for z in {0, 1} if sum(li + [z]) > len(li) - 2))
      
      def report():
        print(f"ONE TWO THREE FOUR FIVE SIX "
        f"SEVEN EIGHT NINE TEN ELEVEN TWELVE"
        f"\n{O+N+E} {T+W+O}   {T+HR+E+E}  {F+O+UR}  {F+I+V+E} {S+I+X} "
        f"  {S+E+V+E+N}   {E+I+GH+T}  {N+I+N+E} {T+E+N}   {E+L+E+V+E+N}"
        f"   {T+W+E+L+V+E}"
        f"\n   O   N   E   T   W   L  HR   F  UR   I   V   S   X  GH"
        f"\n{O:>4}{N:>4}{E:>4}{T:>4}{L:>4}{W:>4}{HR:>4}{F:>4}{UR:>4}"
        f"{I:>4}{V:>4}{S:>4}{X:>4}{GH:>4}")
      
      for (O, N, E) in product(range(mi, ma, step), repeat=3):
        for x1 in {0, 1}:
          if x1 != 0 and O+N+E != 100: continue
          li1 = [x1]
          for (T, x10) in rng(ma, li1):
            if x10 != 0 and T+E+N != 1000: continue
            li2 = li1 + [x10]
            maxW = 201 - 2*mi if sum(li2) == 0 else ma
            for (W, x2) in rng(maxW, li2):
              if x2 != 0 and T+W+O != 200: continue
              li3 = li2 + [x2]
              for (I, x9) in rng(ma, li3):
                if x9 != 0 and N+I+N+E != 900: continue
                li4 = li3 + [x9]
                for L in range(mi, ma, step):
                  for (V, x12) in rng(ma, li4):
                    if x12 != 0 and T+W+E+L+V+E != 1200: continue
                    li5 = li4 + [x12]
                    for x11 in {0, 1}:
                      li6 = li5 + [x11]
                      if sum(li6) < 4 : continue
                      if x11 != 0 and E+L+E+V+E+N != 1100: continue
                      maxF = 501 - 3*mi if sum(li6) == 4 else ma
                      for (F, x5) in rng(maxF, li6):
                        if x5 != 0 and F+I+V+E != 500: continue
                        li7 = li6 + [x5]
                        maxSX = 601 - 2*mi if sum(li7) == 5 else ma
                        for (S, x7) in rng(maxSX, li7):
                          if x7 != 0 and S+E+V+E+N != 700: continue
                          li8 = li7 + [x7]
                          for (X, x6) in rng(maxSX, li8):
                            if x6 != 0 and S+I+X != 600: continue
                            li9 = li8 + [x6]
                            maxGH = 801 - 3*mi if sum(li9) == 7 else ma
                            for (GH, x8) in rng(maxGH, li9):
                              if x8 != 0 and E+I+GH+T != 800: continue
                              li10 = li9 + [x8]
                              maxHR = 301 - 4*mi if sum(li10) == 8 else ma
                              for (HR, x3) in rng(maxHR, li10):
                                if x3 != 0 and T+HR+E+E != 300: continue
                                li11 = li10 + [x3]
                                maxUR = 401 - 3*mi if sum(li11) == 9 else ma
                                for (UR, x4) in rng(maxUR, li11):
                                  if x4 != 0 and F+O+UR != 400: continue
      
                                  r = tuple(li11 + [x4])
                                  if sum(r) != 10: continue  
                                  # only report unique bits
                                  if r not in bits:
                                    report()
                                    bits.add(r)
                                    
      # ONE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN ELEVEN TWELVE
      # 100 200   300  400  500 600   700   800  125 100   1100   1200
      #    O   N   E   T   W   L  HR   F  UR   I   V   S   X  GH
      #   25  25  50  25 550 150 175  50 325  25 375 200 375 700 
      

      Like

      • Jim Randell's avatar

        Jim Randell 5:17 pm on 11 October 2020 Permalink | Reply

        @Frits: The fact that FOUR cannot be one of the incorrect numbers is one of the conditions mentioned in the puzzle text.

        Like

    • GeoffR's avatar

      GeoffR 8:56 am on 12 October 2020 Permalink | Reply

      @Frits: I never used the fact that FOUR cannot be one of the incorrect numbers.
      I only spelt out a condition in the teaser as part of the programme ie F+O+U+R = 400.
      I do not think my programme needs adapting – is OK as the original posting.

      Like

  • Unknown's avatar

    Jim Randell 12:26 pm on 6 October 2020 Permalink | Reply
    Tags:   

    Teaser 2757: Sports quiz 

    From The Sunday Times, 26th July 2015 [link] [link]

    A sports quiz featured one footballer, one cricketer and one rugby player each week. Over the six-week series the footballers featured were (in order) Gerrard, Lambert, Lampard, Rooney, Smalling and Welbeck. The cricketers were (in some order) Carberry, Compton, Robson, Shahzad, Stokes and Tredwell. The rugby players (in some order) were Cipriani, Launchbury, Parling, Robshaw, Trinder and Twelvetrees. Each week, for any two of the three names, there were just two different letters of the alphabet that occurred in both names (with the letters possibly occurring more than once).

    List the cricketers in the order in which they appeared.

    [teaser2757]

     
    • Jim Randell's avatar

      Jim Randell 12:26 pm on 6 October 2020 Permalink | Reply

      Another puzzle by Graham Smithers that can be solved using the [[ grouping ]] routines from the enigma.py library.

      This Python program runs in 46ms.

      Run: [ @repl.it ]

      from enigma import grouping
      
      football = ('Gerrard', 'Lambert', 'Lampard', 'Rooney', 'Smalling', 'Welbeck')
      cricket = ('Carberry', 'Compton', 'Robson', 'Shahzad', 'Stokes', 'Tredwell')
      rugby = ('Cipriani', 'Launchbury', 'Parling', 'Robshaw', 'Trinder', 'Twelvetrees')
      
      grouping.solve([football, cricket, rugby], grouping.share_letters(2))
      

      Solution: The cricketers, in order of appearance are: Shahzad, Robson, Carberry, Tredwell, Compton, Stokes.

      Like

    • Frits's avatar

      Frits 11:36 am on 9 October 2020 Permalink | Reply

      A general solution based on logical rules, I also tested similar grouping puzzles.
      This time I have left the lines to print logical deductions and intermediate solutions.

      NB, does anyone know a solution in Python for splitting print statements (because of 80 chars) so that the code still looks nice? The enigma printf routine also has the same effect as print.

       
      from collections import defaultdict
      from enigma import flatten
      
      label = ["", "single", "pair", "triple", "quadruple", "", "", "", "", "", ""]
      for i in range(5, 11):
        label[i] = str(i) + "-tuple"
      
      # number of shared letters (case insensitive)
      nr_share = lambda a, b: sum(1 for x in set(a.lower()) if x in set(b.lower()))
      
      def report(txt, dict1_2, dict1_3, dict2_3, s1, s2, s3):
        #return
        if txt != "":
          print(f"\n{txt}")
        print(f"\n---------- {s1} - {s2} ------------------------")
        for k, vs in dict1_2.items(): print(f"{k:<12} {vs}")    
        print(f"---------- {s1} - {s3} ------------------------")
        for k, vs in dict1_3.items(): print(f"{k:<12} {vs}")  
        print(f"---------- {s2} - {s3} ------------------------")
        for k, vs in dict2_3.items(): print(f"{k:<12} {vs}")
        print()
        
        
      # check if all dict1_2 and dict1_3 entries have been solved 
      def solved():  
        for k1, vs1 in dict1_2.items():
          if len(vs1) != 1 or len(dict1_3[k1]) != 1:
            return False
        return True  
      
      # look for unique values in dictionary
      def value_unique(di, lst):
        # for each element in lst
        for li in lst:
          uniq = [k for k, vs in di.items() if li in vs]
         
          if len(uniq) == 1 and len(di[uniq[0]]) > 1:
            print(f"unique value {li} in list, \
      {uniq[0]}'s values {di[uniq[0]]} --> {li}")
            di[uniq[0]] = [li]
            reduce_for_nTuples(di)
          
      # look for entries with same dict1_3 and dict2_3 unique value
      def same_list2_list3_value():
        samevals = [(k1, k2) for k1, vs1 in dict1_3.items() 
                    for k2, vs2 in dict2_3.items() if vs1 == vs2 and len(vs1) == 1]
        for k1, k2 in samevals:
          if dict1_2[k1] != [k2]:
            print(f"same value {dict1_3[k1][0]} in 2 and 3, {k1} must be {k2}")
            dict1_2[k1] = [k2]
      
          
      # check for implications of direct relations in dict1_2 
      def reduce_further():
        for k1, vs1 in dict1_2.items():
          if len(vs1) == 1:
            # check other dictionaries
            if len(dict2_3[vs1[0]]) == 1:
              # k1 --> vs1[0], vs1[0] --> unique val2 so val2 belongs to k1
              if dict1_3[k1] != dict2_3[vs1[0]]:
                print(f"{k1} --> {vs1[0]}, {vs1[0]} --> {dict2_3[vs1[0]][0]}: \
      {k1} must be {dict2_3[vs1[0]][0]}")
                dict1_3[k1] = dict2_3[vs1[0]]
                reduce_for_nTuples(dict1_3)
            if len(dict1_3[k1]) == 1:
              if dict2_3[vs1[0]] != dict1_3[k1]:
                print(f"{k1} --> {vs1[0]}, {k1} --> {dict1_3[k1][0]}: \
      {vs1[0]} must be {dict1_3[k1][0]}")
                dict2_3[vs1[0]] = dict1_3[k1]
                reduce_for_nTuples(dict2_3)
                
            # if dict1_2 entry <key1> has only one value <val1>
            # then dict2_3[val1] and dict1_3[key1] must have same values 
            set3 = set(dict2_3[vs1[0]]) & set(dict1_3[k1])
            if len(set3) != len(dict2_3[vs1[0]]) or \
               len(set3) != len(dict1_3[k1]):
      
              #print(k1, vs1, "set3", set3, dict2_3[vs1[0]], dict1_3[k1])
              if len(set3) != len(dict2_3[vs1[0]]):
                print(f"{k1} --> {vs1[0]}, intersection {dict1_3[k1]} and \
      {dict2_3[vs1[0]]} = {set3}\n--> {k1} must be {set3}")
              if len(set3) != len(dict1_3[k1]):
                print(f"{k1} --> {vs1[0]}, intersection {dict1_3[k1]} and \
      {dict2_3[vs1[0]]} = {set3}\n--> {vs1[0]} must be {set3}")
              dict2_3[vs1[0]] = list(set3)
              dict1_3[k1] = list(set3)    
              
      # look for singles, pairs, triples, quads, etc (n-tuples)
      def reduce_for_nTuples(di1, extra=""):
        for i in range(1, len(di1)):
          for k1, vs1 in di1.items():
            if len(vs1) != i: continue
            set1 = set(vs1)
            klist = [k1]
            # collect indices in same <i>-tuple
            for k2, vs2 in di1.items():
              if k2 == k1: continue
              if len(set1 | set(vs2)) == len(set1):
                klist.append(k2)
            
            if len(klist) != i: continue
            
            # klist now contains indices of the <i>-tuple
            # remove <i>-tuple values from other entries in di1
            for k2, vs2 in di1.items():
              if k2 in klist: continue
              for s in set1:
                if s not in vs2: continue
               
                di1[k2].remove(s)
                if len(set1) > 1:  
                  print(f"{label[i]} {set1} for keys {klist}: remove {s} from {k2}")
              
            if extra != "" and i != 1: 
              # check if entries in <i>-tuple have <i> values in dict2_3    
              li = [dict2_3[j] for j in set1]
              # unique values
              set2 = {x for x in flatten(li)}
              if len(set2) != i: continue
      
              # remove values from dict1_3 which are not in set2
              for k in klist:
                for val in dict1_3[k]:
                  if val not in set2:
                    dict1_3[k].remove(val)
                    print(f"{label[i]} {set1} for keys {klist} has to use {set2} \
      \n--> remove {val} from entry {k}")
                        
                       
      # Teaser 2757 
      list1 = ('Gerrard', 'Lambert', 'Lampard', 'Rooney', 'Smalling', 'Welbeck')
      list2 = ('Carberry', 'Compton', 'Robson', 'Shahzad', 'Stokes', 'Tredwell')
      list3 = ('Cipriani', 'Launchbury', 'Parling', 'Robshaw', 'Trinder',
               'Twelvetrees')
         
      (sub1, sub2, sub3) = ("football", "cricket", "rugby")        
      '''
      # Teaser 2816
      list1 = ( 'Dimbleby', 'Evans', 'Mack', 'Marr', 'Norton', 'Peschardt', 'Ross')
      list2 = ( 'Arterton', 'Blunt', 'Carter', 'Jones', 'Knightley', 'Margolyes',
                'Watson')
      list3 = ( 'Bean', 'Caine', 'Cleese', 'Craig', 'De Niro', 'Neeson', 'Oldman')
      
      (sub1, sub2, sub3) = ("hosts", "actresses", "actors")
      
      # Teaser 2892
      
      list1 = ('MARR', 'NEIL', 'NEWMAN', 'PARKINSON', 'PAXMAN', 'POPPLEWELL', 
               'ROBINSON', 'SNOW')
      list2 = ('ABBOTT', 'ABRAHAMS', 'CHAKRABARTI', 'CORBYN', 'EAGLE', 'LEWIS', 
               'STARMER', 'WATSON')
      list3 = ('BRADLEY', 'GRAYLING', 'GREEN', 'HAMMOND', 'LEADSOM', 'LIDINGTON', 
               'MCLOUGHLIN', 'MUNDELL')
       
      (sub1, sub2, sub3) = ("presenters", "labs", "cons")
      
      # Teaser 2682 
      list1 = ('Drax', 'Jaws', 'Krest', 'Largo', 'Morant', 'Moth', 
               'Sanguinette', 'Silva')
      list2 = ('Earth', 'Jupiter', 'Mars', 'Mercury', 'Neptune', 'Saturn', 
               'Uranus', 'Venus')
      list3 = ('Brosnan', 'Casenove', 'Connery', 'Craig', 'Dalton',  'Dench', 
               'Lazenby', 'Moore')
      
      (sub1, sub2, sub3) = ("villain", "planet", "agent")
       '''
      
      dict1_2 = defaultdict(list)
      dict1_3 = defaultdict(list)
      dict2_3 = defaultdict(list)
      
      # initialize dictionaries
      for f in list1:
        for c in list2:
          if nr_share(f, c) == 2:
            dict1_2[f] += [c]
        for r in list3:
          if nr_share(f, r) == 2:
            dict1_3[f] += [r]   
            
      for c in list2:
        for r in list3:
          if nr_share(c, r) == 2:
            dict2_3[c] += [r]     
      
      loop = 0
      while(loop < 7):  
        loop += 1
        print(" ----------------------- loop", loop)
        
        # look for singles, pairs, triples, quads, etc
        reduce_for_nTuples(dict1_2, "extra")
        reduce_for_nTuples(dict1_3)
        reduce_for_nTuples(dict2_3)
      
        report("------ after reduce_for_nTuples", dict1_2, dict1_3, dict2_3, 
               sub1, sub2, sub3)
      
        # look for unique values in dictionary
        value_unique(dict1_2, list2)
        value_unique(dict1_3, list3)
        value_unique(dict2_3, list3)
      
        # check for implications of direct relations in dict1_2 
        reduce_further()
        
        # look for entries with same dict1_3 and dict2_3 unique value
        same_list2_list3_value()
      
      
        report("-- end loop", dict1_2, dict1_3, dict2_3, 
               sub1, sub2, sub3)
      
        if solved():
          print()
          for k1, vs1 in dict1_2.items():
            print(f"{k1:<12} {vs1[0]:<12} {dict1_3[k1][0]:<12}")
          print()  
          break
      

      Like

      • Jim Randell's avatar

        Jim Randell 1:35 pm on 9 October 2020 Permalink | Reply

        @Frits: In Python if two strings appear next to each other they are concatenated by the parser:

        print(
          "<part 1>"
          "<part 2>"
          "<part 3>"
        )
        

        Is the same as:

        print("<part 1><part 2><part 3>")
        

        Like

        • Frits's avatar

          Frits 2:00 pm on 10 October 2020 Permalink | Reply

          Thanks,

          Luckily we have the enigma printf function.

           
          print(f"a1 {sub1} a2")
          print(f"a1 "
                 "{sub1} a2")
          printf("a1 "
                 "{sub1} a2")      
                 
          # a1 villain a2
          # a1 {sub1} a2
          # a1 villain a2       
          

          Like

          • Jim Randell's avatar

            Jim Randell 2:20 pm on 10 October 2020 Permalink | Reply

            @Frits: The f"..." construct in Python 3 is also a string:

            >>> (x, y) = ("this", "that")
            >>> print(
              f"{x}"
              " and "
              f"{y}"
            )
            this and that
            

            Like

  • Unknown's avatar

    Jim Randell 10:20 am on 4 October 2020 Permalink | Reply
    Tags: by: A. J. Weight   

    Brain-Teaser 9: Whose daughter? 

    From The Sunday Times, 23rd April 1961 [link]

    Mrs. A, Mrs. B and Mrs. C and their three daughters bought materials for dresses. Each lady spent as many shillings per yard as she bought yards. Each mother spent £5 5s more than her daughter. Mrs. A bought 11 yards more than Florence, and Mrs. C spent £6 15s less than Patricia. The other daughter’s name was Mary.

    Whose daughter was each?

    Note: £1 = 20s.

    [teaser9]

     
    • Jim Randell's avatar

      Jim Randell 10:21 am on 4 October 2020 Permalink | Reply

      Working in shillings. (There are 20s to £1).

      For any of the ladies, if the price per yard of the material was x (shillings per yard), then that lady bought x yards, and so spent x² shillings.

      And each mother spent 105 shillings more than her daughter, so we are looking for solutions to:

      x² − y² = 105

      where x is the value for the mother and y is the value for the daughter.

      We can solve this equation for integer values, by considering divisors of 105:

      (x + y)(x − y) = 105

      This Python program runs in 47ms.

      Run: [ @repl.it ]

      from enigma import (divisors_pairs, div, Record, subsets, sq, printf)
      
      # find solutions to x^2 - y^2 = 105 (over positive integers)
      xys = list(Record(x=div(b + a, 2), y=div(b - a, 2)) for (a, b) in divisors_pairs(105))
      
      # choose (mother, daughter) pairs
      (A, B, C) = (0, 1, 2)
      for ss in subsets(xys, size=3, select='P'):
      
        # choose daughters to be F, M, P
        for (F, M, P) in subsets((A, B, C), size=len, select='P'):
      
          # "Mrs A bought 11 yards more than F"
          if not (ss[A].x - ss[F].y == 11): continue
      
          # "Mrs C spent 135s less than P"
          if not (sq(ss[C].x) + 135 == sq(ss[P].y)): continue
      
          ns = "ABC"
          printf("{F}+F {M}+M {P}+P [A={A} B={B} C={C}]", F=ns[F], M=ns[M], P=ns[P], A=ss[A], B=ss[B], C=ss[C])
      

      Solution: Patricia is Mrs. A’s daughter. Florence is Mrs. B’s daughter. Mary is Mrs. C’s daughter.

      The number of yards bought, and number of shillings spent is:

      Mrs. A = 19; P = 16
      Mrs. B = 13; F = 8
      Mrs. C = 11; M = 4

      There are only four solutions to the equation x² − y² = 105. The unused one is: (x = 53, y = 52).

      Like

    • Frits's avatar

      Frits 7:10 pm on 4 October 2020 Permalink | Reply

      A Solution in MiniZinc.

      I am not very happy with the output statements.
      Does anyone know a better way?

      include "globals.mzn";
       
      var  12..53: A;
      var  11..53: B;
      var  11..51: C;
      % daughters
      var  1..52: DA;
      var  1..52: DB;
      var  1..52: DC;
      
      var  1..52: M;
      var  12..52: P;
      var  1..42: F;
       
      % Mrs. A bought 11 yards more than Florence
      constraint F + 11 = A;
      % Mrs. C spent 6pnd 15s less than Patricia
      constraint C * C + 135 = P * P;
      
      % Each mother spent 5pnd 5s more than her daughter
      constraint  A * A == DA * DA + 105;
      constraint  B * B == DB * DB + 105;
      constraint  C * C == DC * DC + 105;
      % Florence is not Mrs. A's daughter
      constraint  DA != F;
      % Patricia is not Mrs. C's daughter
      constraint  DC != P;
      
      % DA, DB, DC is the same list as F, M, P
      constraint sort([DA, DB, DC]) = sort([F, M, P]);
       
      solve satisfy;
      
      output [if fix(DA)==fix(P) then "Mrs A's daughter is Patrica\n" 
             else if fix(DA)==fix(M) then "Mrs A's daughter is Mary\n"
             else "Mrs A's daughter is Florence\n" endif endif];
      
      output [if fix(DB)==fix(P) then "Mrs B's daughter is Patrica\n" 
             else if fix(DB)==fix(M) then "Mrs B's daughter is Mary\n"
             else "Mrs B's daughter is Florence\n" endif endif];
      
      output [if fix(DC)==fix(P) then "Mrs C's daughter is Patrica\n" 
             else if fix(DC)==fix(M) then "Mrs C's daughter is Mary\n"
             else "Mrs C's daughter is Florence\n" endif endif];
             
      % Mrs A's daughter is Patrica
      % Mrs B's daughter is Florence
      % Mrs C's daughter is Mary       
      

      Like

    • Brian Gladman's avatar

      Brian Gladman 10:34 am on 8 October 2020 Permalink | Reply

      @Frits As you have found, MiniZinc is great for certain types of problems but its output facilities are poor to say the least. But Jim has provided an excellent Python wrapper for MiniZInc and like Jim I pretty well always use this rather than MiniZinc. The wrapper also has the further advantage that multiple MiniZInc outputs can be further processed and this allows hybrid MiniZinc/Python solutions that can gain the best from both worlds.

      Like

      • Frits's avatar

        Frits 11:46 am on 9 October 2020 Permalink | Reply

        @Jim and Brian
        Thanks.

        I tried to make a user defined function in MiniZinc but that took me too much effort.
        I also have to get used to the way the MiniZinc documentation has been set up.

        Like

  • Unknown's avatar

    Jim Randell 4:49 pm on 2 October 2020 Permalink | Reply
    Tags:   

    Teaser 3028: Rainbow numeration 

    From The Sunday Times, 4th October 2020 [link] [link]

    Dai had seven standard dice, one in each colour of the rainbow (ROYGBIV). Throwing them simultaneously, flukily, each possible score (1 to 6) showed uppermost. Lining up the dice three ways, Dai made three different seven-digit numbers: the smallest possible, the largest possible, and the “rainbow” (ROYGBIV) value. He noticed that, comparing any two numbers, only the central digit was the same, and also that each number had just one single-digit prime factor (a different prime for each of the three numbers).

    Hiding the dice from his sister Di’s view, he told her what he’d done and what he’d noticed, and asked her to guess the “rainbow” number digits in ROYGBIV order. Luckily guessing the red and orange dice scores correctly, she then calculated the others unambiguously.

    What score was on the indigo die?

    I’ve changed the wording of the puzzle slightly to make it clearer.

    [teaser3028]

     
    • Jim Randell's avatar

      Jim Randell 5:17 pm on 2 October 2020 Permalink | Reply

      (Note: I’ve updated my program (and the puzzle text) in light of the comment by Frits below).

      This Python program runs in 49ms.

      Run: [ @repl.it ]

      from enigma import irange, subsets, nconcat, filter_unique, printf
      
      # single digit prime divisor
      def sdpd(n):
        ps = list(p for p in (2, 3, 5, 7) if n % p == 0)
        return (ps[0] if len(ps) == 1 else None)
      
      # if flag = 0, check all values are the same
      # if flag = 1, check all values are different
      check = lambda flag, vs: len(set(vs)) == (len(vs) if flag else 1)
      
      # all 6 digits are represented
      digits = list(irange(1, 6))
      
      # but one of them is repeated
      ans = set()
      for (i, d) in enumerate(digits):
        ds = list(digits)
        ds.insert(i, d)
        # make the smallest and largest numbers
        smallest = nconcat(ds)
        p1 = sdpd(smallest)
        if p1 is None: continue
        largest = nconcat(ds[::-1])
        p2 = sdpd(largest)
        if p2 is None or p2 == p1: continue
        printf("smallest = {smallest} ({p1}); largest = {largest} ({p2})")
      
        # find possible "rainbow" numbers
        rs = list()
        for s in subsets(ds[:3] + ds[4:], size=len, select="P", fn=list):
          s.insert(3, ds[3])
          # rainbow has only the central digit in common with smallest and largest
          if not all(check(i != 3, vs) for (i, vs) in enumerate(zip(s, ds, ds[::-1]))): continue
          rainbow = nconcat(s)
          p3 = sdpd(rainbow)
          if p3 is None or not check(1, (p1, p2, p3)): continue
      
          rs.append(tuple(s))
      
        # find rainbow numbers unique by first 2 digits
        for rainbow in filter_unique(rs, (lambda s: s[:2])).unique:
          n = nconcat(rainbow)
          printf("-> rainbow = {n} ({p3})", p3=sdpd(n))
          # record the indigo value
          ans.add(rainbow[5])
      
      # output solution
      printf("indigo = {ans}")
      

      Solution: The score on the indigo die is 4.

      Each of the digits 1-6 is used once, and there is an extra copy of one of them. So there is only one possible set of 7 digits used.

      The smallest number is: 1234456 (divisible by 2).

      And the largest number is: 6544321 (divisibly by 7).

      There are 17 possible values for the “rainbow” number, but only 3 of them are uniquely identified by the first 2 digits: 2314645, 3124645, 3614245 (and each is divisible by 5).

      The scores on the green, indigo and violet dice are the same for all three possible “rainbow” numbers: 4, 4, 5. So this gives us our answer.

      Like

    • Frits's avatar

      Frits 11:02 pm on 2 October 2020 Permalink | Reply

      “each number had just one prime factor under 10 (different for each number)”.

      The three numbers you report seem to have same prime factors under 10, maybe I have misunderstood.

      Like

      • Jim Randell's avatar

        Jim Randell 11:10 pm on 2 October 2020 Permalink | Reply

        @Frits: I think you could be right. I took it to mean that it wasn’t the same prime in each case (two of the numbers I originally found share a prime). But requiring there to be three different primes does also give a unique answer to the puzzle (different from my original solution). So it could well be the correct interpretation (and it would explain why we weren’t asked to give the rainbow number). Thanks.

        Like

    • Frits's avatar

      Frits 11:35 pm on 2 October 2020 Permalink | Reply

      @Jim: I hope to publish my program tomorrow (for three different prime numbers). I don’t have a clean program yet.

      Your solution also seems to be independent of the indigo question (it could have been asked for another colour). In my solution this specific colour is vital for the solution.

      Like

    • Frits's avatar

      Frits 11:26 am on 3 October 2020 Permalink | Reply

      Next time I try to use the insert function (list).

       
      from enigma import factor, irange, concat, peek 
      from itertools import permutations as perm
      from collections import defaultdict
      
      P = {2, 3, 5, 7}
      
      # number of same characters at same positions
      nr_common = lambda x, y: sum(1 for i, a in enumerate(x) if a == y[i])
      
      # prime factors under 10
      factund10 = lambda x: [p for p in P if int(x) % p == 0]
      
      # if list contains one entry then return possible values at position i
      charvals = lambda s, i: {x[0][i] for x in s if len(x) == 1}
      
      n = 6
      digits = concat([x for x in irange(1, n)])
      
      # for each digit i occuring twice in lowest and highest number
      for i in irange(1, n):
        str_i = str(i)
        # build lowest and highest number
        low = digits[:i] + str_i + digits[i:]
        hgh = low[::-1]
       
        # get prime factors under 10 
        u10low = factund10(low) 
        u10hgh = factund10(hgh) 
        
        # each number with one prime factor under 10 (different for each number)
        if len(u10low) != 1 or len(u10hgh) != 1 or u10low[0] == u10hgh[0]:
           continue
       
        rainbow = defaultdict(list)
       
        # for this combination of lowest and highest check the rainbow possibilities
        for pe in perm(low[:n//2] + low[n//2 + 1:]):
          # weave central digit into permutation pe at center position
          rb = concat(pe[:n//2] + tuple(low[n//2]) + pe[n//2:])
          
          # check rainbow number on only the central digit being the same
          if nr_common(rb, low) != 1 or nr_common(rb, hgh) != 1: 
            continue
      
          u10rb = factund10(int(rb)) 
          # all three prime factors under 10 are different
          if len(u10rb) == 1 and u10rb[0] != u10low[0] and u10rb[0] != u10hgh[0]:
            # store rainbow number with as key first 2 digits
            rainbow[rb[:2]].append(rb)
            
        # if first 2 digits rainbow number is unique then list indigo values
        indigo = charvals(rainbow.values(), 5)  
        if len(indigo) == 1:
          print(f"The score on the indigo die: {peek(indigo)}")
      

      Like

    • Frits's avatar

      Frits 2:58 pm on 4 October 2020 Permalink | Reply

      A more efficient program (without explaining the choices as this is a new puzzle).

       
      from enigma import factor, irange, concat, diff 
      from itertools import permutations as perm
      from collections import defaultdict
      
      # number of same characters at same positions
      nr_common = lambda x, y: sum(1 for i, a in enumerate(x) if a == y[i])
      
      # prime factors under 10
      factund10 = lambda x: [p for p in {2, 5, 7} if int(x) % p == 0]
      
      # if list contains one entry then return possible values at position i
      charvals = lambda s, i: {x[0][i] for x in s if len(x) == 1}
      
      n = 6
      digits = concat([x for x in irange(1, n)])
      
      # for each digit i occuring twice in lowest and highest number
      for i in irange(1, n):
        if i % 3 == 0: continue
        
        # build lowest and highest number
        low = digits[:i] + str(i) + digits[i:]
        hgh = low[::-1]
       
        # get prime factors under 10 
        u10low = factund10(low)       
        u10hgh = factund10(hgh)       
       
        if len(u10hgh) != 1 or u10hgh[0] != 7: continue
        
        # each number with one prime factor under 10 (different for each number)
        if len(u10low) != 1: continue
        
        rainbow = defaultdict(list)
         
        # for this combination of lowest and highest check the rainbow possibilities
        center = str(i)
        remaining = diff(low[:n//2] + low[n//2 + 1:], "5")
        # try possibilities for first digit  
        for d1 in diff(remaining, "1" + str(n)):
          # find values for positions without the edges and the center
          for pe2 in perm(diff(remaining, d1) , n - 2):
            # build rainbow number
            rb = d1 + concat(pe2[:(n-1)//2]) + center + \
                 concat(pe2[(n-1)//2:]) + "5"
            
            if int(rb) % u10hgh[0] == 0:      
              continue
           
            # check rainbow number on only the central digit being the same
            if nr_common(rb, low) != 1 or nr_common(rb, hgh) != 1: 
              continue
            
            # store rainbow number with as key first 2 digits
            rainbow[rb[:2]].append(rb)
        
        # if first 2 digits rainbow number is unique then list indigo values
        indigo = charvals(rainbow.values(), 5)  
        if len(indigo) == 1:
          print(f"The score on the indigo die: {indigo.pop()}")  
      

      Like

  • Unknown's avatar

    Jim Randell 8:55 am on 1 October 2020 Permalink | Reply
    Tags:   

    Teaser 2544: Neighbourly nonprimes 

    From The Sunday Times, 26th June 2011 [link] [link]

    I live in a long road with houses numbered 1 to 150 on one side. My house is in a group of consecutively numbered houses where the numbers are all nonprime, but at each end of the group the next house number beyond is prime. There are a nonprime number of houses in this group. If I told you the lowest prime number which is a factor of at least one of my two next-door neighbours’ house numbers, then you should be able to work out my house number.

    What is it?

    [teaser2544]

     
    • Jim Randell's avatar

      Jim Randell 8:55 am on 1 October 2020 Permalink | Reply

      I implemented the [[ chop() ]] function, which chops a sequence into contiguous segments that give the same value for a function. This can then be used to select the segments of contiguous non-primes.

      We can use a little shortcut to check if a prime p divides one of the neighbours of n. If we consider the product of the neighbours ((n − 1) and (n + 1)), then if the prime divides the product, it must divide one of the neighbours. Now:

      (n − 1)(n + 1) = n² − 1

      So, if the residue of n² modulo p is 1, then p divides one of the neighbours of n.

      The following Python program runs in 47ms.

      from enigma import (irange, primes, peek, filter_unique, printf)
      
      # chop sequence s into segments that give the same value for function f
      # return pairs of (f-value, segment)
      def chop(f, s):
        (fv, ss) = (None, [])
        for x in s:
          v = f(x)
          if v == fv:
            ss.append(x)
          else:
            if ss: yield (fv, ss)
            (fv, ss) = (v, [x])
        if ss: yield (fv, ss)
      
      # primes up to 150
      primes.expand(150)
      
      # consider segments of non-primes
      for (fv, ss) in chop(primes.is_prime, irange(1, 150)):
        if fv: continue
        # the length of the segment is non-prime (but > 1)
        n = len(ss)
        if n < 2 or n in primes: continue
      
        # the lowest prime number that is a factor of at least one of my neighbours
        # house numbers uniquely identifies my house number
        f = lambda n: peek(p for p in primes if (n * n) % p == 1)
        hs = filter_unique(ss, f).unique
      
        # output solution
        printf("group = {ss}; house = {hs}")
      

      Solution: Your house number is 144.

      It turns out there is only one segment of non-primes (in the specified range) that has a (non-unity) non-prime length:

      (140, 141, 142, 143, 144, 145, 146, 147, 148)

      It contains 9 numbers.

      And the lowest prime factor of the neighbours uniquely identifies one of the numbers. So it must be an even number, and they all have a smallest-neighbour-factor of 3, except for 144 which has a smallest-neighbour-factor of 5.

      Like

      • Jim Randell's avatar

        Jim Randell 12:57 pm on 1 October 2020 Permalink | Reply

        Or even simpler:

        Run: [ @replit ]

        from enigma import (irange, primes, tuples, peek, filter_unique, printf)
        
        # consider 2 consecutive primes
        for (a, b) in tuples(primes.between(2, 150), 2):
          # with a non-prime number of non-primes in between
          n = b - a - 1
          if n < 2 or n in primes: continue
          (a, b) = (a + 1, b - 1)
        
          # the lowest prime number that is a factor of at least one of my neighbours
          # house numbers uniquely identifies my house number
          f = lambda n: peek(p for p in primes if (n * n) % p == 1)
          hs = filter_unique(irange(a, b), f).unique
        
          # output solution
          printf("group = [{a} .. {b}]; house = {hs}")
        

        Like

        • Frits's avatar

          Frits 5:05 pm on 1 October 2020 Permalink | Reply

          Nice,

          The output is a little different from the previous program.
          (the definition of a group excludes prime numbers)

          filter_unique also works with a+1 and b-1.

          Like

          • Jim Randell's avatar

            Jim Randell 5:23 pm on 1 October 2020 Permalink | Reply

            @Frits: Yes, you are right. The range should exclude the primes. I’ve fixed it up now.

            Like

    • Frits's avatar

      Frits 10:31 am on 1 October 2020 Permalink | Reply

      [reorder=0] clause was necessary for a decent run time (100 ms).

       
      from enigma import SubstitutedExpression, is_prime
          
      # the alphametic puzzle
      p = SubstitutedExpression(
        [ 
          "A < 2",  # speed up process
          "ABC < 148",
          "D < 2 and D >= A",  # speed up process
          "DEF > ABC + 2",
          "DEF < 151",
          # Find 2 prime numbers
          "is_prime(ABC)",
          "is_prime(DEF)",
          # There are a nonprime number of houses in this group
          "not is_prime(DEF - ABC - 1)",
          # with no other prime numbers between ABC and DEF
          "sum(1 for i in range(ABC + 1, DEF) if is_prime(i)) == 0",
          # my house number MNO lies in such a group
          "M < 2 and M >= A",  # speed up process
          "MNO > ABC",
          "MNO < DEF",
          # my neighbour on one side
          "MNO - 1 = UVW",
          # my neighbour on the other side
          "MNO + 1 = XYZ",
          # lowest prime number which is a factor of at least one of my 
          # neighbours' house numbers
          "min([x for x in range(2, 150) if UVW % x == 0 and is_prime(x)]) = JKL",
          "min([x for x in range(2, 150) if XYZ % x == 0 and is_prime(x)]) = GHI",
        ],
        answer="(min(GHI, JKL), MNO)",
        verbose=0,
        d2i="",        # allow number representations to start with 0
        distinct="",   # allow variables with same values
        reorder=0,
      )
       
      # solve puzzle
      answs = [y for _, y in p.solve()]
      
      # only print answers with a unique first element
      if len(answs) > 0:
        print("My house number:", [a[1] for a in answs 
              if [x[0] for x in answs].count(a[0]) == 1][0])
      
      # My house number: 144
      

      Like

  • Unknown's avatar

    Jim Randell 9:10 am on 29 September 2020 Permalink | Reply
    Tags:   

    Teaser 1904: Neat answer 

    From The Sunday Times, 14th March 1999 [link]

    I have started with a four-figure number with its digits in decreasing order. I have reversed the order of the four digits to give a smaller number. I have subtracted the second from the first to give a four-figure answer, and I have seen that the answer uses the same four digits — very neat!

    Substituting letters for digits, with different letters being consistently used for different digits, my answer was NEAT!

    What, in letters, was the four-figure number I started with?

    This puzzle is included in the book Brainteasers (2002). The puzzle text above is taken from the book.

    [teaser1904]

     
    • Jim Randell's avatar

      Jim Randell 9:19 am on 29 September 2020 Permalink | Reply

      We can use the [[ SubstitutedExpression ]] solver from the enigma.py library to solve this puzzle.

      The following run file executes in 91ms.

      Run: [ @replit ]

      #! python -m enigma -rr
      
      SubstitutedExpression
      
      "WXYZ - ZYXW = NEAT"
      "ordered(N, E, A, T) == (Z, Y, X, W)"
      
      --distinct="WXYZ,NEAT"
      --answer="translate({WXYZ}, str({NEAT}), 'NEAT')"
      

      Solution: The initial 4-figure number is represented by: ANTE.

      So the alphametic sum is: ANTEETNA = NEAT.

      And the corresponding digits: 7641 − 1467 = 6174.

      Like

    • Hugh Casement's avatar

      Hugh Casement 1:37 pm on 29 September 2020 Permalink | Reply

      If we had not been told the digits were in decreasing order there would have been three other solutions:
      2961 – 1692 = 1269, 5823 – 3285 = 2538, 9108 – 8019 = 1089.

      Like

      • Finbarr Morley's avatar

        Finbarr Morley 10:58 am on 24 November 2020 Permalink | Reply

        I’m not sure that’s right:
        2961-1692= 1269
        ANTE-ETNA=EATN
        It’s true, but it’s not NEAT!

        Like

        • Jim Randell's avatar

          Jim Randell 8:57 am on 25 November 2020 Permalink | Reply

          The result of the sum is NEAT by definition.

          Without the condition that digits in the number you start with are in descending order, we do indeed get 4 different solutions. Setting the result to NEAT, we find they correspond to four different alphametic expressions:

          9108 − 8019 = 1089 / TNEAAENT = NEAT
          5823 − 3285 = 2538 / ETNAANTE = NEAT
          7641 − 1467 = 6174 / ANTEETNA = NEAT
          2961 − 1692 = 1269 / ETANNATE = NEAT

          Like

    • GeoffR's avatar

      GeoffR 6:30 pm on 29 September 2020 Permalink | Reply

      
      from itertools import permutations
      from enigma import nreverse, nsplit
      
      for p1 in permutations((9, 8, 7, 6, 5, 4, 3, 2, 1, 0), 4):
        W, X, Y, Z = p1
        if W > X > Y > Z:
          WXYZ = 1000 * W + 100 * X + 10 * Y + Z
          ZYXW = nreverse(WXYZ)
          NEAT = WXYZ - ZYXW
          N, E, A, T = nsplit(NEAT)
          # check sets of digits are the same
          if {W, X, Y, Z} == {N, E, A, T}:
            print(f"Sum is {WXYZ} - {ZYXW} = {NEAT}")
      
      # Sum is 7641 - 1467 = 6174
      
      

      Like

    • GeoffR's avatar

      GeoffR 8:56 am on 25 November 2020 Permalink | Reply

      I checked Hugh’s assertion, changing my programme to suit, and it looks as though he is correct.
      My revised programme gave the original correct answer and the three extra answers, as suggested by Hugh.
      @Finnbarr:
      If we take NEAT = 1269, then ETAN – NATE = NEAT – (Sum is 2961 – 1692 = 1269)

      
      from itertools import permutations
      from enigma import nreverse, nsplit
       
      for p1 in permutations((9, 8, 7, 6, 5, 4, 3, 2, 1,0), 4):
          W, X, Y, Z = p1
          #if W > X > Y > Z:
          WXYZ = 1000 * W + 100 * X + 10 * Y + Z
          ZYXW = nreverse(WXYZ)
          NEAT = WXYZ - ZYXW
          if NEAT > 1000 and WXYZ > 1000 and ZYXW > 1000:
              N, E, A, T = nsplit(NEAT)
              # check sets of digits are the same
              if {W, X, Y, Z} == {N, E, A, T}:
                print(f"Sum is {WXYZ} - {ZYXW} = {NEAT}")
       
      # Sum is 9108 - 8019 = 1089
      # Sum is 7641 - 1467 = 6174  << main answer
      # Sum is 5823 - 3285 = 2538
      # Sum is 2961 - 1692 = 1269
      
      

      Like

    • Finbarr Morley's avatar

      Finbarr Morley 9:41 am on 30 November 2020 Permalink | Reply

      A maths student would view this as 4 unknowns (A,N,T, & E) and 4 Equations.
      So it can be uniquely solved with simultaneous equations.

      And there’s a neat ‘trick’ recognising the pairs of letters:

      A E
      E A

      And

      N T
      T N

      The ANSWER is the easy bit:

      ANTE
      7641

      The SOLUTION is as follows:

      Column 4321
             ANTE
           - ETNA
           = NEAT
      

      From the 1,000’s column 4 we seen that A>E, otherwise the answer would be negative.
      ∴ in the 1’s column, (where E is less than A) E must borrow 1 from the T in the 10’s column:

      Col.   2        1
             T-1   10+E
             N        A
             A        T  
      

      There are 2 scenarios:
      (A) N>T
      (B) N<T

      As before, T in the 10’s column must borrow 1 from the N in the 100’s column.

          4    3     2       1
          A  N-1  10+T-1  10+E             
        - E    T     N       A
        = N    E     A       T
      

      The equations for each of the 4 columns are:

      (1) 10+E-A = T
      (2) 10+T-1-N = A
      (3) N-1-T = E
      (4) A-E = N

      Rearrange to:

      (1) A-E = 10-T
      (4) A-E = N

      (2) N-T = 9-A
      (3) N-T = E+1

      (1-4) 10-T = N (because they both equal A-E) rearrange to N+T = 10
      (2-3) 9-A = E+1 (because they both equal N-T) rearrange to A+E = 8

      From here either solve by substituting numbers, or with algebra.

      SUBSTITUTION:

      A+E=8 and A>E. So A = 5,6,7 or 8

      A   E     A-E=N     N+T=10
      5   3         2       8  N>T
      6   2         4       6  N>T
      7   1         6       4  *** THIS IS THE ONLY SOLUTION ***
      8   0         8	      2 can’t have 2 numbers the same
      

      ALGERBRA:

                N+T=10             A+E=8
           (2)-(N-T=9-A)      (1)+(A-E=10-T)	
                 2T=1+A  			                    2A    =(18-T)
       (x2)      4T=2+(2A)
      
      ∴   4T=2+(18-T)   
          5T=20
           T=4
      ∴    N=6 (N+T=10)
      ∴    E=1  (N-T=1+E)
      ∴    A=7  (A+E=8)
      

      Check assumption (A) N>T TRUE (6>4)

      ANSWER:
      ANTE 7641
      - ETNA – 1467
      = NEAT = 6174

      Like

      • Finbarr Morley's avatar

        Finbarr Morley 9:43 am on 30 November 2020 Permalink | Reply

        Now repeat for Assumption (B) N < T, to see if it is valid.

        Equations are similar but different:

        This time the N in the 100’s column must borrow 1 from the A in the 1000’s column.

           4      3      2      1
        
          A-1   10+N    T-1   10+E             
        
        -  E      T      N      A
        
        =  N      E      A      T
        

        The equations for each of the 4 columns are:

        (1) 10+E-A=T (exactly the same as before)

        (2) T-1-N=A

        (3) 10+N-T=E

        (4) A-1-E=N

        Rearrange to:

        (1) A-E = 10-T

        (4) A-E = N+1

        (2) T-N = A+1

        (3) T-N = 10-E

        (1-4) 10-T=N+1 (because they both equal A-E) rearrange to T+N=9

        (2-3) A+1=10-E (because they both equal T-N) rearrange to A+E=9

        From here either solve by substituting numbers, or with algebra.

        SUBSTITUTION:

        A+E=9 and A>E.

        So A = 5,6,7 or 8 or 9

        A   E     A-E=N+1     N+T=9      T-N=10-E
        5   4         0         9           no           
        6   3         2         7           no
        7   2         4         5           no
        8   1         6         3           N<T
        9   0         8         1           N<T
        

        There are no valid answers with N<T.

        ALGEBRA:

                  T+N = 9               A+E = 9
              2) +T-N = A+1        1) +(A-E = 10-T)	
                 2T   = 10+A           2A   = 19-T
             x2) 4T   = 20+2A
        
        ∴   4T = 20+19-T   
            3T = 39
             T = 13
        

        Since this is not 0 to 9, the assumption (B) N<T is invalid.

        Assumption A is the only valid solution.

        There can be only one – William Shakespeare

        Like

        • Jim Randell's avatar

          Jim Randell 11:55 am on 30 November 2020 Permalink | Reply

          @Finbarr: Thanks for your comments. (And I hope I’ve tidied them up OK).

          Although I think we can take a bit of a shortcut:

          If we start with:

          WXYZ + ZYXW = NEAT
          where: W > X > Y > Z

          Then considering the columns of the sum we have:

          (units) T = 10 + ZW
          (10s) A = 9 + YX
          (100s) E = X − 1 − Y
          (1000s) N = WZ

          Then, (units) + (1000s) and (10s) + (100s) give:

          N + T = 10
          A + E = 8

          which could be used to shorten your solution.

          Like

          • Jim Randell's avatar

            Jim Randell 1:53 pm on 30 November 2020 Permalink | Reply

            Or we can extend it into a full solution by case analysis:

            Firstly, we see Z ≠ 0, as ZYXW is a 4-digit number.

            And W > 5, as 5 + 4 + 3 + 2 < 18.

            So considering possible values for W:

            [W = 6]

            There is only one possible descending sequence that sums to 18, i.e. (6, 5, 4, 3)

            So the sum is:

            6543 − 3456 = 3087

            which doesn’t work.

            [W = 7]

            W must be paired with 3 (to make 10) or 1 (to make 8).

            If it is paired with 3, then the other pair is 2+6. So the sum is:

            7632 − 2367 = 5265

            which doesn’t work.

            If it is paired with 1, then the other pair is either 2+8 or 4+6, which gives us the following sums:

            8721 − 1278 = 7443
            7641 − 1467 = 6174

            The first doesn’t work, but the second gives a viable solution: ANTEETNA = NEAT.

            And the following cases show uniqueness:

            [W = 8]

            W must be paired with 2, and the other pair is either 1+7 or 3+5, and we have already looked at (8, 7, 2, 1)

            8532 − 2358 = 6174

            This doesn’t work.

            [W = 9]

            W must be paired with 1, and the other pair either 2+6 or 3+5:

            9621 − 1269 = 8352
            9531 − 1359 = 8173

            Neither of these work.

            Like

    • Finbarr Morley's avatar

      Finbarr Morley 3:14 pm on 30 November 2020 Permalink | Reply

      I’m curious about the properties of these Cryptarithmetics.
      How is it that ANTE-ETNA=NEAT has 1 unique solution out of 10,000.
      But ANTE-ETNA=NAET has none?

      A Google search reveals some discussion:
      http://cryptarithms.awardspace.us/primer.html
      https://www.codeproject.com/Articles/176768/Cryptarithmetic
      https://onlinelibrary.wiley.com/doi/abs/10.1111/j.1949-8594.1987.tb11711.x

      The latter seems to be heading for a discussion on the rules, but it’s ony the first page of an extract.
      Any thoughts from the collective on what the natural rules are?

      Like

  • Unknown's avatar

    Jim Randell 8:55 am on 27 September 2020 Permalink | Reply
    Tags:   

    Teaser 1892: Puzzling present 

    From The Sunday Times, 20th December 1998 [link]

    I have received an astonishing letter from a fellow puzzle-setter. He writes:

    “I am sending you a puzzle in the form of a parcel consisting of an opaque box containing some identical marbles, each weighing a whole number of grams, greater than one gram. The box itself is virtually weightless. If I told you the total weight of the marbles, you could work out how many there are.”

    He goes on:

    “To enable you to work out the total weight of the marbles I am also sending you a balance and a set of equal weights, each weighing a whole number of grams, whose total weight is two kilograms. Bearing in mind what I told you above, these weights will enable you to calculate the total weight of the marbles and hence how many marbles there are.”

    I thought that he was sending me these items under seperate cover, but I had forgotten how mean he is. He went on:

    “I realise that I can save on the postage. If I told you the weight of each weight you would still be able to work out the number of marbles. Therefore I shall not be sending you anything.”

    How many marbles were there?

    This puzzle is included in the book Brainteasers (2002). The puzzle text above is taken from the book.

    [teaser1892]

     
    • Jim Randell's avatar

      Jim Randell 8:55 am on 27 September 2020 Permalink | Reply

      (See also: Enigma 1606).

      There must be a prime number of balls, each weighing the same prime number of grams.

      This Python program uses the same approach I took with Enigma 1606 (indeed if given a command line argument of 4000 (= the 4kg total of the weights) it can be used to solve that puzzle too).

      It runs in 48ms.

      Run: [ @repl.it ]

      from enigma import Primes, isqrt, divisor, group, arg, printf
      
      # total weights
      T = arg(2000, 0, int)
      
      # find prime squares up to T
      squares = list(p * p for p in Primes(isqrt(T)))
      
      printf("[T={T}, squares={squares}]")
      
      # each weight is a divisor of T
      for w in divisor(T):
      
        # make a "by" function for weight w
        def by(p):
          (k, r) = divmod(p, w)
          return (k if r > 0 else -k)
      
        # group the squares into categories by the number of weights required
        d = group(squares, by=by)
        # look for categories with only one weight in
        ss = list(vs[0] for vs in d.values() if len(vs) == 1)
        # there should be only one
        if len(ss) != 1: continue
      
        # output solution
        p = ss[0]
        printf("{n}x {w}g weights", n=T // w)
        printf("-> {p}g falls into a {w}g category by itself")
        printf("-> {p}g = {r} balls @ {r}g each", r=isqrt(p))
        printf()
      

      Solution: There are 37 marbles.

      There are 4× 500g weights (2000g in total), and when these are used to weigh the box we must find that it weighs between 1000g (2 weights) and 1500g (3 weights). The only prime square between these weights is 37² = 1369, so there must be 37 balls each weighing 37g.

      Telling us that “if I told you the weight of the weights you would be able to work out the number of marbles” is enough for us to work out the number of marbles, without needing to tell us the actual weight. (As there is only one set of weights that gives a category with a single prime square in). And we can also deduce the set of weights.

      However, in a variation on the puzzle where the set of weights total 2200g, we find there are two possible sets of weights that give a category with a single square in (8× 275g and 4× 550g), but in both cases it is still 1369 that falls into a category by itself, so we can determine the number (and weight) of the marbles, but not the weight (and number) of the weights. So the answer to the puzzle would still be the same.

      Likewise, if the set of weights total 3468g, there are 3 possible sets of weights that give a category with a single square in (6× 578g, 4× 867g and 3× 1156g). However in each of these cases 2809 falls into a category by itself, and so the solution would be 53 marbles each weighing 53g. Which is the answer to Enigma 1606.

      Like

    • Frits's avatar

      Frits 11:36 pm on 27 September 2020 Permalink | Reply

       
      from enigma import SubstitutedExpression
      from collections import defaultdict
      
      # list of prime numbers
      P = {2, 3, 5, 7}
      P |= {x for x in range(11, 45, 2) if all(x % p for p in P)}
      # list of squared prime numbers
      P2 = [p * p for p in P]
      
      # check if only one total lies uniquely between k weights and k+1 weights
      def uniquerange(weight):
        group = defaultdict(list)
        for total in P2:
          # total lies between k weights and k+1 weights
          k = total // weight
          if group[k]:
            group[k].append(total)
          else:
            group[k] = [total]
      
        singles = [group[x][0] for x in group if len(group[x]) == 1]
        if len(singles) == 1:
          return singles[0]
          
        return 0  
            
      # the alphametic puzzle
      p = SubstitutedExpression(
        [ # ABCD is a weight and a divisor of 2000
          "2000 % ABCD == 0",
          "uniquerange(ABCD) != 0",
        ],
        answer="(ABCD, uniquerange(ABCD))",
        env=dict(uniquerange=uniquerange), # external functions
        verbose=0,
        d2i="",        # allow number representations to start with 0
        distinct="",   # allow variables with same values
      )
       
      # Print answers
      for (_, ans) in p.solve():
        print(f"{int(2000/ans[0])} x {ans[0]}g weigths")
        print(f"-> {ans[1]}g falls into a {ans[0]}g category by itself")
        print(f"-> {ans[1]}g = {ans[1] ** 0.5} balls @ {ans[1] ** 0.5}g each")
      

      Like

  • Unknown's avatar

    Jim Randell 4:40 pm on 25 September 2020 Permalink | Reply
    Tags:   

    Teaser 3027: Long shot 

    From The Sunday Times, 27th September 2020 [link] [link]

    Callum and Liam play a simple dice game together using standard dice (numbered 1 to 6). A first round merely determines how many dice (up to a maximum of three) each player can use in the second round. The winner is the player with the highest total on their dice in the second round.

    In a recent game Callum was able to throw more dice than Liam in the second round but his total still gave Liam a chance to win. If Liam had been able to throw a different number of dice (no more than three), his chance of winning would be a whole number of times greater.

    What was Callum’s score in the final round?

    [teaser3027]

     
    • Jim Randell's avatar

      Jim Randell 5:13 pm on 25 September 2020 Permalink | Reply

      This Python program runs in 49ms.

      Run: [ @repl.it ]

      from enigma import (multiset, subsets, irange, div, printf)
      
      # calculate possible scores with 1, 2, 3 dice
      fn = lambda k: multiset.from_seq(sum(s) for s in subsets(irange(1, 6), size=k, select="M"))
      scores = dict((k, fn(k)) for k in (1, 2, 3))
      
      # choose number of dice for Liam and Callum (L < C)
      for (kL, kC) in subsets(sorted(scores.keys()), size=2):
        (C, L) = (scores[kC], scores[kL])
        tL = len(L)
        # consider scores for Callum
        for sC in C.keys():
          # and calculate Liam's chance of winning
          nL = sum(n for (s, n) in L.items() if s > sC)
          if nL == 0: continue
      
          # but if Liam had been able to throw a different number of dice, his
          # chance of winning would be a whole number of times greater (L < H)
          for (kH, H) in scores.items():
            if not (kH > kL): continue
            tH = len(H)
            nH = sum(n for (s, n) in H.items() if s > sC)
            d = div(nH * tL, nL * tH)
            if d is None or not(d > 1): continue
      
            # output solution
            printf("Callum: {kC} dice, score = {sC} -> Liam: {kL} dice, chance = {nL} / {tL}")
            printf("-> Liam: {kH} dice, chance = {nH} / {tH} = {d} times greater")
            printf()
      

      Solution: Callum scored 10 in the final round.

      The result of the first round was that Callum was to throw 3 dice, and Liam was to throw 2.

      Callum scored 10 on his throw. Which meant that Liam had a chance to win by scoring 11 (two ways out of 36) or 12 (one way out of 36), giving a total chance of 3/36 (= 1/12) of winning the game.

      However if Liam had been able to throw 3 dice, he would have had a total chance of 108/216 (= 1/2 = 6/12) of scoring 11 to 18 and winning the game. This is 6 times larger.

      Like

  • Unknown's avatar

    Jim Randell 12:59 pm on 24 September 2020 Permalink | Reply
    Tags:   

    Teaser 2756: Terrible teens 

    From The Sunday Times, 19th July 2015 [link] [link]

    I have allocated a numerical value (possibly negative) to each letter of the alphabet, where some different letters may have the same value. I can now work out the value of any word by adding up the values of its individual letters. In this way NONE has value 0, ONE has value 1, TWO has value 2, and so on up to ELEVEN having value 11. Unfortunately, looking at the words for the numbers TWELVE to NINETEEN, I find that only two have values equal to the number itself.

    Which two?

    [teaser2756]

     
    • Jim Randell's avatar

      Jim Randell 1:01 pm on 24 September 2020 Permalink | Reply

      (See also: Enigma 1602).

      A manual solution:

      From:

      NONE = 0
      ONE = 1

      we see:

      N = −1

      We can write the unknown words in terms of the known words:

      TWELVE = TWO + ELEVENONE = 12
      THIRTEEN = THREE + TEN + IE = 13 + IE
      FOURTEEN = FOUR + TEN + E = 14 + E
      FIFTEEN = FIVE + TEN + FV = 15 + FV
      SIXTEEN = SIX + TEN + E = 16 + E
      SEVENTEEN = SEVEN + TEN + E = 17 + E
      EIGHTEEN = EIGHT + TEN + ET = 18 + ET
      NINETEEN = NINE + TEN + E = 19 + E

      We see the value of TWELVE is fixed as 12, so this is one of the correct unknown words. So there is only one left to find.

      Note if E = 0, then FOURTEEN, SIXTEEN, SEVENTEEN, NINETEEN are all correct, which is not possible, so E ≠ 0 (and they are all incorrect).

      So the possibilities for the other correct word are:

      THIRTEENI = E
      FIFTEENF = V
      EIGHTEENT = E

      In the first case, when THIRTEEN = 13, we have I = E, so we can substitute I with E.

      So, for NINE and EIGHTEEN:

      N = −1
      NENE = 9 ⇒ EE = 11
      EEGHTEEN = EEGHT + EE + N = 8 + 11 − 1 = 18

      So if THIRTEEN is correct, so is EIGHTEEN.

      And if EIGHTEEN = 18, we have T = E, so for THIRTEEN:

      N = −1
      NINE = 9 ⇒ NINEN = 9 − (−1) = 10
      EHIREEEN = EHREE + NINEN = 3 + 10 = 13

      So THIRTEEN and EIGHTEEN are either both correct (impossible) or both incorrect.

      Which means the only remaining viable solution is FIFTEEN = 15, and so F = V.

      Putting together what we already have and solving the equations gives the following values:

      F = −3
      N = −1
      V = −3

      I = 11 − E
      L = 15 − 3E
      O = 2 − E
      S = 11 − 2E
      T = 11 − E
      W = 2E − 11
      X = 3E − 16
      GH = E − 14
      HR = −E − 8
      UR = E + 5

      TWELVE = 12 [CORRECT]
      THIRTEEN = 24 − 2E
      FOURTEEN = 14 + E
      FIFTEEN = 15 [CORRECT]
      SIXTEEN = 16 + E
      SEVENTEEN = 17 + E
      EIGHTEEN = 7 + 2E
      NINETEEN = 19 + E

      Which makes TWELVE and FIFTEEN the other correct words, providing: E ≠ 0, E ≠ 11/2.

      Solution: TWELVE and FIFTEEN are correct.

      Like

    • Frits's avatar

      Frits 4:55 pm on 24 September 2020 Permalink | Reply

      @Jim,

      I like your equation

      TWELVE = TWO + ELEVEN – ONE = 12

       
      # N+O+N+E = 0 and O+N+E = 1 so N = - 1
      #
      # F+O+U+R+T+E+E+N, S+I+X+T+E+E+N, S+E+V+E+N+T+E+E+N and N+I+N+E+T+E+E+N
      # are all incorrect, they are of the form ...+T+E+E+N 
      # where ... already is an equation. T+E+E+N can't be 10 as not all of
      # the 4 numbers can be correct.
      #
      # Remaining correct candidates are:
      # T+W+E+L+V+E, T+H+I+R+T+E+E+N, F+I+F+T+E+E+N and E+I+G+H+T+E+E+N 
      #
      # E+I+G+H+T+E+E+N = 8+E+E+N = 7+E+E, this can never be 18 
      #
      # T+E+N = T+E-1 = 10, so T = 11 - E
      # N+I+N+E = I+E-2 = 9, so I = 11 - E
      # T+H+I+R+T+E+E+N = 3+I+T+N = 2+I+T = 24 - 2E, this can never be 13 
      # so answer must be T+W+E+L+V+E and F+I+F+T+E+E+N
      

      Like

      • Jim Randell's avatar

        Jim Randell 5:15 pm on 24 September 2020 Permalink | Reply

        @Frits: I take it you are assuming the values are integers. It’s a reasonable assumption, although not explicitly stated (and not actually necessary to solve the puzzle).

        Although if we allow fractions in both cases we get E = 11/2, so in this scenario both THIRTEEN = 13 and EIGHTEEN = 18 would be true, and we would have too many correct values.

        The TWO + ELEVEN = TWELVE + ONE equality also cropped up in Enigma 1278 (where fractions were explicitly allowed).

        Also I changed your enclosure to use:

        [code language="text" gutter="false"]
        ...
        [/code]
        

        Which turns off syntax highlighting and line numbers.

        Like

    • John Crabtree's avatar

      John Crabtree 5:30 am on 25 September 2020 Permalink | Reply

      TEN + NONE = NINE + ONE, and so I = T
      and so THIRTEEN + EIGHTEEN = THREE + TEN + (I – E) + EIGHT + TEN +(E – T) = 31
      And so THIRTEEN and EIGHTEEN are both correct, or both incorrect.

      Like

    • GeoffR's avatar

      GeoffR 8:11 am on 25 September 2020 Permalink | Reply

      
      % A Solution in MiniZinc
      include "globals.mzn";
       
      var -25..25: O; var -25..25: N; var -25..25: E;
      var -25..25: T; var -25..25: W; var -25..25: H;
      var -25..25: R; var -25..25: F; var -25..25: U;
      var -25..25: I; var -25..25: V; var -25..25: S;
      var -25..25: X; var -25..25: G; var -25..25: L;
       
      % Numbers NONE .. ELEVEN are all correct 
      constraint N+O+N+E = 0 /\ O+N+E = 1 /\ T+W+O = 2 
      /\ T+H+R+E+E = 3 /\ F+O+U+R = 4 /\ F+I+V+E = 5
      /\ S+I+X = 6 /\ S+E+V+E+N = 7 /\ E+I+G+H+T = 8 
      /\ N+I+N+E = 9 /\ T+E+N = 10 /\ E+L+E+V+E+N = 11;
                
      % Exactly two of TWELVE .. NINETEEN are correct
      constraint sum ( [
      T+W+E+L+V+E == 12, T+H+I+R+T+E+E+N == 13, 
      F+O+U+R+T+E+E+N == 14, F+I+F+T+E+E+N == 15,
      S+I+X+T+E+E+N == 16, S+E+V+E+N+T+E+E+N == 17, 
      E+I+G+H+T+E+E+N == 18, N+I+N+E+T+E+E+N == 19] ) == 2;
      
      solve satisfy;
       
      output [ "TWELVE = ", show (T+W+E+L+V+E), 
               ", THIRTEEN = ", show(T+H+I+R+T+E+E+N),
               ", FOURTEEN = ", show(F+O+U+R+T+E+E+N), 
               ", FIFTEEN = ", show(F+I+F+T+E+E+N),
               ",\nSIXTEEN = ", show(S+I+X+T+E+E+N), 
               ", SEVENTEEN = ", show(S+E+V+E+N+T+E+E+N),
               ", EIGHTEEN = ", show(E+I+G+H+T+E+E+N), 
               ", NINETEEN = ", show(N+I+N+E+T+E+E+N)  ];
      
      % TWELVE = 12, THIRTEEN = 30, FOURTEEN = 11, FIFTEEN = 15,
      % SIXTEEN = 13, SEVENTEEN = 14, EIGHTEEN = 1, NINETEEN = 16
      
      % Answer: Only numbers TWELVE and FIFTEEN are correct
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 2:06 pm on 22 September 2020 Permalink | Reply
    Tags:   

    Teaser 2755: Female domination 

    From The Sunday Times, 12th July 2015 [link] [link]

    In the village of Alphaville, the number of females divided by the number of males was a certain whole number. Then one man and his wife moved into the village and the result was that the number of females divided by the number of males was one less than before. Now today two more such married couples have moved into the village, but the number of females divided by the number of males is still a whole number.

    What is the population of the village now?

    [teaser2755]

     
    • Jim Randell's avatar

      Jim Randell 2:07 pm on 22 September 2020 Permalink | Reply

      I think this Teaser marks the start of my regular solving (i.e. I solved all subsequent Teasers at the time of their publication). So I should have notes that enable me to fill in the gaps of Teasers set after this one. (Currently I have posted all Teasers from Teaser 2880 onwards, and quite a few earlier ones – there are currently 353 Teasers available on the site). So in some ways it corresponds to Enigma 1482 on the Enigmatic Code site.

      This Python program runs in 45ms.

      Run: [ @replit ]

      from enigma import (irange, inf, divisors_pairs, div, printf)
      
      # generate solutions
      def solve():
        # consider total population
        for t in irange(2, inf):
          # divide the population into males and females
          for (d, m) in divisors_pairs(t, every=1):
            if d < 2: continue
            # p = initial f / m ratio
            p = d - 1
            f = t - m
            # ratio (f + 1) / (m + 1) = p - 1
            if not ((p - 1) * (m + 1) == f + 1): continue
            # ratio (f + 3) / (m + 3) is an integer
            q = div(f + 3, m + 3)
            if q is None: continue
            # final population (after 3 extra couples have moved in)
            yield (t + 6, m, f, p, q)
      
      # find the first solution
      for (pop, m, f, p, q) in solve():
        printf("final population = {pop} [m={m} f={f} p={p} q={q}]")
        break
      

      Solution: The population of the village is now 24.

      Initially there were 3 males and 15 females in the village (initial ratio = 15 / 3 = 5).

      The addition of one couple gave 4 males and 16 females (new ratio = 16 / 4 = 4).

      And the addition of two extra couples gives 6 males and 18 females (final ratio = 18 / 6 = 3).

      So the final population is: 6 + 18 = 24.


      Manually:

      Initially the ratio of females to males is an integer p:

      p = f / m
      f = p.m

      The ratio changes to (p − 1) with 1 more male and 1 more female:

      (p − 1) = (f + 1) / (m + 1)
      (p − 1) = (p.m + 1) / (m + 1)
      (p − 1)(m + 1) = p.m + 1
      p.m + p − m − 1 = p.m + 1
      p = m + 2

      And the ratio (f + 3) / (m + 3) is also an integer q:

      (p.m + 3) / (m + 3) = q
      ((m + 2)m + 3) / (m + 3) = q
      (m² + 2m + 3) / (m + 3) = q
      (m − 1) + 6 / (m + 3) = q

      So (m + 3) is a divisor of 6, greater than 3. i.e. (m + 3) = 6, so m = 3:

      m = 3
      p = 5
      f = 15
      q = 3

      So the solution is unique.

      Like

  • Unknown's avatar

    Jim Randell 9:40 am on 20 September 2020 Permalink | Reply
    Tags: by: C. S. Mence,   

    Brain-Teaser 8: Cat and dog 

    From The Sunday Times, 16th April 1961 [link]

    In the block of flats where I live there are 4 dogs and 4 cats. The 4 flat numbers, where the dogs are kept, multiplied together = 3,570, but added = my flat number. The 4 numbers, where the cats are kept, multiplied together also = 3,570, but added = 10 less than mine. Some flats keep both a dog and a cat, but there is only one instance of a dog and a cat being kept in adjacent flats.

    At what number do I live, and where are the dogs and cats kept?

    [teaser8]

     
    • Jim Randell's avatar

      Jim Randell 9:41 am on 20 September 2020 Permalink | Reply

      As it is written there are multiple solutions to this puzzle.

      However, we can narrow these down to a single solution (which is the same as the published solution) with the additional condition: “No dogs or cats are kept in flat number 1”.

      This Python program runs in 48ms.

      from enigma import (cproduct, divisor, group, is_disjoint, printf)
      
      # decompose p into k increasing numbers (which when multiplied together give p)
      def decompose(p, k, m=1, s=[]):
        if k == 1:
          if not (p < m):
            yield s + [p]
        else:
          # choose a divisor of p
          for x in divisor(p):
            if not (x < m):
              yield from decompose(p // x, k - 1, x, s + [x])
      
      # collect 4-decompositions of 3570 by sum
      d = group(decompose(3570, 4), by=sum)
      
      # consider possible flat numbers (= sum of dogs)
      for (t, dogs) in d.items():
        # sum of cats is t - 10
        cats = d.get(t - 10, [])
        for (ds, cs) in cproduct([dogs, cats]):
          # some flats keep both a dog and a cat
          if is_disjoint([ds, cs]): continue
          # there is only one instance of a dog and a cat in adjacently numbered flats
          if sum(abs(d - c) == 1 for (d, c) in cproduct([ds, cs])) != 1: continue
          # output solution
          printf("flat={t}: dogs={ds} cats={cs}")
      

      Solution: As set there are 9 possible solutions:

      flat=125, dogs=[1, 2, 17, 105], cats=[1, 5, 7, 102]
      flat=109, dogs=[1, 2, 21, 85], cats=[1, 6, 7, 85]
      flat=99, dogs=[1, 6, 7, 85], cats=[1, 2, 35, 51]
      flat=69, dogs=[1, 7, 10, 51], cats=[1, 6, 17, 35]
      flat=57, dogs=[1, 7, 15, 34], cats=[1, 14, 15, 17]
      flat=55, dogs=[1, 7, 17, 30], cats=[2, 5, 17, 21]
      flat=57, dogs=[2, 3, 17, 35], cats=[1, 14, 15, 17]
      flat=65, dogs=[2, 5, 7, 51], cats=[1, 7, 17, 30]
      flat=45, dogs=[2, 5, 17, 21], cats=[5, 6, 7, 17]

      However, if we eliminate solutions involving flat number 1 then we find only one of these solutions remains:

      flat=45, dogs=[2, 5, 17, 21], cats=[5, 6, 7, 17]

      And this is the published solution. So perhaps the setter “forgot” about 1 when looking at divisors of 3570.

      The following (apology?) was published with Teaser 9:

      Dogs kept at Nos. 2, 5, 17 and 21; cats at 5, 6, 7 and 17. I live at No. 45. This is not a unique solution and no correct entry was rejected.

      We can adjust the program for this variation by setting the m parameter of decompose() to 2 in line 16:

      d = group(decompose(3570, 4, 2), by=sum)
      

      Like

    • Frits's avatar

      Frits 2:04 pm on 20 September 2020 Permalink | Reply

      Limiting flat numbers to 1-199.

       
      from enigma import SubstitutedExpression, join, printf 
      
      #  only one instance of a dog and a cat being kept in adjacent flats  
      adj = lambda li1, li2: sum(1 for x in li1 if x - 1 in li2 or x + 1 in li2)
      
      p = SubstitutedExpression([
          "ABC * DEF * GHI * JKL = 3570",
          "ABC + DEF + GHI + JKL == xyz",
          "MNO * PQR * STU * VWX = 3570",
          "MNO + PQR + STU + VWX + 10 == xyz",
          # numbers are factors of 3570
          "3570 % ABC == 0",
          "3570 % DEF == 0",
          "3570 % GHI == 0",    
          "3570 % JKL == 0",
          "3570 % MNO == 0",
          "3570 % PQR == 0",
          "3570 % STU == 0",
          "3570 % VWX == 0",
          # flat numbers are ascending
          "ABC < DEF",
          "DEF < GHI",
          "GHI < JKL", 
          "MNO < PQR",
          "PQR < STU",
          "STU < VWX",
          # speed up process by limiting range to (1, 199)
          "A < 2", "D < 2", "G < 2", "J < 2",
          "M < 2", "P < 2", "S < 2", "V < 2",
          # only one instance of a dog and a cat being kept in adjacent flats
          "adj([ABC, DEF, GHI, JKL], [MNO, PQR,STU, VWX]) == 1",
          ],
          verbose=0,
          symbols="ABCDEFGHIJKLMNOPQRSTUVWXxyz",
          answer="(ABC, DEF, GHI, JKL, MNO, PQR,STU, VWX, xyz)",
          env=dict(adj=adj), # external functions
          d2i="",            # allow number respresentations to start with 0
          distinct="",       # letters may have same values                     
      )
      
      
      # Solve and print answer
      for (_, ans) in p.solve(): 
        printf("dogs: {p1:<10} - cats: {p2:<11}  Mine={ans[8]}", 
               p1 = join(ans[:4], sep = " "),
               p2 = join(ans[4:8], sep = " "))
      
      # Output:
      #
      # dogs: 1 2 21 85  - cats: 1 6 7 85     Mine=109
      # dogs: 1 6 7 85   - cats: 1 2 35 51    Mine=99
      # dogs: 1 7 10 51  - cats: 1 6 17 35    Mine=69
      # dogs: 1 7 15 34  - cats: 1 14 15 17   Mine=57
      # dogs: 1 7 17 30  - cats: 2 5 17 21    Mine=55
      # dogs: 2 3 17 35  - cats: 1 14 15 17   Mine=57
      # dogs: 2 5 7 51   - cats: 1 7 17 30    Mine=65
      # dogs: 2 5 17 21  - cats: 5 6 7 17     Mine=45
      # dogs: 1 2 17 105 - cats: 1 5 7 102    Mine=125
      

      Like

    • Ellen Napier's avatar

      Ellen Napier 1:03 am on 27 December 2025 Permalink | Reply

      Since “some flats keep both” is plural, I took the number of flats having both
      a dog and a cat to be at least two. That reduces the number of solutions from
      9 to 3.

      An alternative edit (admittedly more complex) would be to change “one instance
      of a cat and a dog” to “one instance of a cat and a cat’s canine companion”,
      which also produces the published solution.

      Like

  • Unknown's avatar

    Jim Randell 5:13 pm on 18 September 2020 Permalink | Reply
    Tags:   

    Teaser 3026: Party time 

    From The Sunday Times, 20th September 2020 [link] [link]

    A four-digit number with different positive digits and with the number represented by its last two digits a multiple of the number represented by its first two digits, is called a PAR.

    A pair of PARs is a PARTY if no digit is repeated and each PAR is a multiple of the missing positive digit.

    I wrote down a PAR and challenged Sam to use it to make a PARTY. He was successful.

    I then challenged Beth to use my PAR and the digits in Sam’s PAR to make a different PARTY. She too was successful.

    What was my PAR?

    [teaser3026]

     
    • Jim Randell's avatar

      Jim Randell 5:30 pm on 18 September 2020 Permalink | Reply

      This Python program uses the [[ SubstitutedExpression() ]] general alphametic solver from the enigma.py library to find possible PARTYs. It then collects pairs of PARs together and looks for a PAR that has two possible pairings that share the same digits.

      It runs in 56ms.

      Run: [ @replit ]

      from enigma import (defaultdict, SubstitutedExpression, irange, subsets, nsplit, printf)
      
      # find possible PARTYs (ABCD, EFGH, X)
      p = SubstitutedExpression(
        ["CD % AB = 0", "ABCD % X = 0", "GH % EF = 0", "EFGH % X = 0", "ABCD < EFGH"],
        digits=irange(1, 9),
        answer="(ABCD, EFGH, X)",
        verbose=0
      )
      
      # collect results by PARs
      d = defaultdict(list)
      for (ABCD, EFGH, X) in p.answers():
        d[ABCD].append(EFGH)
        d[EFGH].append(ABCD)
      
      # collect the digits of a number
      digits = lambda n: sorted(nsplit(n))
      
      # choose the initial PAR
      for (k, vs) in d.items():
        # choose two related PARs ...
        for (p1, p2) in subsets(vs, size=2):
          # ... that have the same digits
          if digits(p1) == digits(p2):
            printf("{k} -> {p1}, {p2}")
      

      Solution: Your PAR was 1785.

      1785 can be paired with both 2496 and 4692 (missing digit = 3) to make a PARTY.

      There are 7 possible PARTYs:

      (1938, 2754, 6)
      (1854, 3672, 9)
      (1836, 2754, 9)
      (1785, 4692, 3)
      (1785, 2496, 3)
      (1734, 2958, 6)
      (1456, 3978, 2)

      There are only 2 PARs that appear in more than one PARTY: 1785 and 2754. Each of these appears in two PARTYs, but only 1785 is paired with two other PARs that share the same digits.

      Like

      • Jim Randell's avatar

        Jim Randell 12:28 pm on 20 September 2020 Permalink | Reply

        Using the [[ SubstitutedExpression ]] general alphametic solver from the enigma.py library.

        This run file executes in 94ms.

        Run: [ @replit ]

        #! python3 -m enigma -rr
        
        SubstitutedExpression
        
        # Graham's PAR = ABCD
        "CD % AB = 0"
        
        # Sam's PAR = EFGH ...
        "GH % EF = 0"
        
        # ... makes a PARTY with ABCD and X
        "ABCD % X = 0"
        "EFGH % X = 0"
        
        # Beth's PAR = IJKL ...
        "KL % IJ = 0"
        
        # ... makes a different PARTY with ABCD and X
        "IJKL % X = 0"
        "EFGH != IJKL"
        
        # solver parameters
        --digits="1-9"
        --distinct="ABCDEFGHX,ABCDIJKLX"
        --answer="ABCD"
        

        Like

    • Frits's avatar

      Frits 9:12 pm on 19 September 2020 Permalink | Reply

       
      from enigma import nconcat
      from itertools import permutations, combinations
       
      difference = lambda a, b: [x for x in a if x not in b]  
       
      def getPARs(ds, k):
        li = []
        # check all permutations of digits
        for p1 in permutations(ds): 
          # first digit can't be high
          if p1[0] > 4: continue
          
          n12 = nconcat(p1[:2])
          n34 = nconcat(p1[2:])
          n = 100 * n12 + n34
          # number last two digits is a multiple of number first 2 digits
          # and four-digit number is a multiple of k
          if n34 % n12 != 0 or n % k != 0: continue
          # store the PAR 
          li.append(n)
        return li  
            
      sol = [] 
      # loop over missing digits 
      for k in range(1,10):
        digits = difference(range(1,10), [k])
        # choose the lowest remaining digit
        low = min(digits)
        digits = difference(digits, [low])
        # pick 3 digits to complement low
        for c1 in combinations (digits, 3): 
          par1 = getPARs((low,) + c1, k) 
          if par1: 
            par2 = getPARs(difference(digits, c1), k) 
            # PAR(s) related to two or more PARs?
            if len(par1) == 1 and len(par2) == 1:
              continue
            if len(par2) == 1: 
              sol.append([par2, par1])
            elif par2:
              sol.append([par1, par2])
           
      for i in range(len(sol)):
        print(f"{sol[i][0]} --> {sol[i][1]}")
      

      Like

    • Will Harris's avatar

      Will Harris 3:14 pm on 19 December 2020 Permalink | Reply

      Not much help now but wrote this for my coursework project using GNU prolog [ https://www.tutorialspoint.com/execute_prolog_online.php ]

      :- initialization(main).
      % This program has been developed for GNU Prolog | https://www.tutorialspoint.com/execute_prolog_online.php
      
      %Question 2.1
      convert(P, Q) :-
          Q is P - 48,
          Q > 0.
      
      unique(List) :-
          sort(List, Sorted),
          length(List, OriginalLength),
          length(Sorted, SortedLength),
          OriginalLength =:= SortedLength.
      
      multiple_of([A,B,C,D]) :-
          get_num(A,B,X),
          get_num(C,D,Y),
          check_mod(X,Y).
          
      get_num(P,Q,R) :-
          R is P * 10 + Q.
      
      check_mod(N,M) :-
          M mod N =:= 0.
          
      par(Number) :-
          number_codes(Number,ListCharCodes), 
          maplist(convert,ListCharCodes,ListDigits),
          length(ListDigits, 4),
          unique(ListDigits),
          multiple_of(ListDigits).
      
      
      %Question 2.2
      candidate_pars(P, Q, []) :-
          P > Q.
      candidate_pars(P, Q, [P|W]) :-
          par(P),
          P1 is P + 1,
          candidate_pars(P1, Q, W).
      candidate_pars(P, Q, W) :- 
          P1 is P + 1,
          candidate_pars(P1, Q, W).
      
      pars( PARS ) :-
          candidate_pars(1234, 9876, PARS).
      
      
      %Question 2.3
      missing_digit(V,W,CombDigits) :-
          number_codes(V, ListOne),
          number_codes(W, ListTwo),
          maplist(convert, ListOne, ListDigitsOne),
          maplist(convert, ListTwo, ListDigitsTwo),
          append(ListDigitsOne, ListDigitsTwo, CombDigits).
      
      party(V, W) :-
          missing_digit(V, W, CombDigits),
          subtract([1,2,3,4,5,6,7,8,9], CombDigits, MissingDigits),
          length(MissingDigits, 1),
          par(V),
          par(W),
          nth(1, MissingDigits, M),
          check_mod(M,V),
          check_mod(M,W).
      
      
      %Question 2.4
      comparison(PARS, I, J) :-
          member(I, PARS), 
          member(J, PARS), 
          party(I,J).
      
      partys( PARTYS ) :-
          pars(PARS),
          findall([I,J], comparison(PARS, I, J), PARTYS).
      
      main :-
          partys( PARTYS ), write(PARTYS).
      
      /*
      There is only a single solution to Teaser 3026:
      There are only 2 PARs that appear in more than one PARTY: 1785 and 2754. 
      Each of these appears in two PARTYs, but only 1785 is paired with two other
      PARs that share the same digits. 1785 can be paired with both 2496 and 4692 
      (missing digit = 3) to make a PARTY.
      */
      

      Like

      • Jim Randell's avatar

        Jim Randell 3:26 pm on 19 December 2020 Permalink | Reply

        @Will: Thanks for your comment.

        I’m not sure if the code came through correctly (WordPress can get confused by text with < and > characters in it).

        If it’s wrong, can you post again with the code in:

        [code]
        code goes here
        [/code]
        

        and I’ll fix it up.

        Like

    • GeoffR's avatar

      GeoffR 4:57 pm on 16 December 2021 Permalink | Reply

      
      from itertools import permutations
      
      digits = set('123456789')
      
      for p1 in permutations(digits, 5):
          A, B, C, D, I = p1
          # my PAR is ABCD and I is the missing digit
          ABCD = int(A + B + C + D)
          if ABCD % int(I) !=0: continue
          AB, CD = int(A + B), int(C + D)
          if not(CD % AB == 0):continue
          
          # find another two PARs to make two PARTYs
          q1 = digits.difference(p1)
          for p2 in permutations(q1):
              E, F, G, H = p2
              EFGH = int(E + F + G + H)
              if not EFGH % int(I) == 0: continue
              EF, GH = int(E + F), int(G + H)
              if not (GH % EF == 0):continue
              
              # form 2nd PAR with digits (E, F, G, H)
              for p3 in permutations(p2):
                  e, f, g, h = p3
                  efgh = int(e + f + g + h)
                  # there must be two different PARs from EFGH
                  if EFGH == efgh:continue
                  if efgh % int(I) != 0: continue
                  ef, gh = int(e + f), int(g + h)
                  if not (gh % ef == 0):continue
                  print(f"My PAR = {ABCD}")
                  print(f"Sam / Beth's PARTY = {ABCD}, {EFGH}")
                  print(f"Sam / Beth's PARTY = {ABCD}, {efgh}")
                  print()
      
      # My PAR = 1785
      # Sam / Beth's PARTY = 1785, 4692
      # Sam / Beth's PARTY = 1785, 2496
      
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 11:59 am on 17 September 2020 Permalink | Reply
    Tags:   

    Teaser 2736: HS2 

    From The Sunday Times, 1st March 2015 [link] [link]

    Last night I dreamt that I made a train journey on the HS2 line. The journey was a whole number of miles in length and it took less than an hour. From the starting station the train accelerated steadily to its maximum speed of 220 mph, then it continued at that speed for a while, and finally it decelerated steadily to the finishing station. If you took the number of minutes that the train was travelling at a steady speed and reversed the order of its two digits, then you got the number of minutes for the whole journey.

    How many miles long was the journey?

    [teaser2736]

     
    • Jim Randell's avatar

      Jim Randell 12:00 pm on 17 September 2020 Permalink | Reply

      If the time at constant speed is AB minutes, then the total time is BA minutes, and:

      AB < BA < 60

      So:

      0 < A < B < 6

      The maximum speed is 220 mph = 11/3 miles per minute.

      From the velocity/time graph we get the total distance d is:

      d = (121/6)(A + B)

      From which we see (A + B) must be divisible by 6, so (A, B) = (1, 5) or (2, 4), and d = 121.

      A simple Python program can verify this:

      from enigma import (subsets, irange, div, printf)
      
      for (A, B) in subsets(irange(1, 5), size=2):
        d = div(121 * (A + B), 6)
        if d is not None:
          printf("d={d} [A={A} B={B}]")
      

      Solution: The journey was 121 miles long.

      Like

  • Unknown's avatar

    Jim Randell 8:31 am on 15 September 2020 Permalink | Reply
    Tags: ,   

    Teaser 2719: Foursums 

    From The Sunday Times, 2nd November 2014 [link] [link]

    In a woodwork lesson the class was given a list of four different non-zero digits. Each student’s task was to construct a rectangular sheet whose sides were two-figure numbers of centimetres with the two lengths, between them, using the four given digits. Pat constructed the smallest possible such rectangle and his friend constructed the largest possible. The areas of these two rectangles differed by half a square metre.

    What were the four digits?

    [teaser2719]

     
    • Jim Randell's avatar

      Jim Randell 8:32 am on 15 September 2020 Permalink | Reply

      This Python program runs in 55ms.

      Run: [ @repl.it ]

      from enigma import (subsets, irange, Accumulator, partitions, product, nconcat, join, printf)
      
      # generate (width, height) pairs from digits <ds>
      def generate(ds):
        for (ws, hs) in partitions(ds, 2):
          for (w, h) in product((ws, ws[::-1]), (hs, hs[::-1])):
            yield (nconcat(w), nconcat(h))
      
      # choose 4 different non-zero digits
      for ds in subsets(irange(1, 9), size=4):
        # record the min/max areas
        rs = Accumulator.multi(fns=[min, max])
      
        # form the digits into width, height pairs
        for (w, h) in generate(ds):
          # calculate the area: A = ab x cd
          A = w * h
          rs.accumulate_data(A, (w, h))
      
        # do the max and min areas differ by 5000 cm^2 ?
        (mn, mx) = rs
        if mx.value - mn.value == 5000:
          printf("digits = {ds}")
          printf("-> min area = {mn.value} = {wh}", wh=join(mn.data, sep=" x "))
          printf("-> max area = {mx.value} = {wh}", wh=join(mx.data, sep=" x "))
          printf()
      

      Solution: The four digits are: 1, 6, 7, 8.

      The minimum area is: 17 × 68 = 1156.

      The maximum area is: 81 × 76 = 6156.

      Like

    • Frits's avatar

      Frits 11:55 pm on 15 September 2020 Permalink | Reply

       
      from enigma import SubstitutedExpression, irange, subsets
      
      # determine smallest possible rectangle 
      def mini(A, B, C, D):
        minimum = 9999
        for s in subsets(str(A)+str(B)+str(C)+str(D), size=4, select="P"):
          area = (int(s[0])*10 + int(s[1])) * (int(s[2])*10 + int(s[3]))
          minimum = min(minimum, area)
        return minimum  
        
      # determine larges possible rectangle
      def maxi(A, B, C, D):
        maximum = 0 
        for s in subsets(str(A)+str(B)+str(C)+str(D), size=4, select="P"):
          area = (int(s[0])*10 + int(s[1])) * (int(s[2])*10 + int(s[3]))
          maximum = max(maximum, area)
        return maximum   
          
      
      p = SubstitutedExpression([
          "(maxi(A, B, C, D) - mini(A, B, C, D)) == 5000",
          # only report a solution once
          "A < B",
          "B < C", 
          "C < D", 
          ],
          verbose=0,
          answer="(A, B, C, D)",
          env=dict(mini=mini, maxi=maxi), # external functions
          digits=irange(1, 9),
      )
      
      # Solve and print answer
      print("Answer")
      for (_, ans) in p.solve(): 
        print(ans)
      
      
      # Output:
      #
      # Answer
      # (1, 6, 7, 8)
      

      Like

      • Frits's avatar

        Frits 11:59 pm on 15 September 2020 Permalink | Reply

        Also possible is to determine the smallest and largest possible rectangle in one function/loop.

        Like

      • Jim Randell's avatar

        Jim Randell 2:15 pm on 16 September 2020 Permalink | Reply

        @Frits: There’s no need to turn the digits into strings and back.

        Here’s a version that just operates on the digits directly:

        from enigma import (SubstitutedExpression, irange, subsets, nconcat)
         
        # determine smallest possible rectangle 
        def mini(A, B, C, D):
          minimum = 9999
          for s in subsets((A, B, C, D), size=4, select="P"):
            area = nconcat(s[:2]) * nconcat(s[2:])
            minimum = min(minimum, area)
          return minimum  
           
        # determine larges possible rectangle
        def maxi(A, B, C, D):
          maximum = 0
          for s in subsets((A, B, C, D), size=4, select="P"):
            area = nconcat(s[:2]) * nconcat(s[2:])
            maximum = max(maximum, area)
          return maximum   
         
        p = SubstitutedExpression([
              "(maxi(A, B, C, D) - mini(A, B, C, D)) = 5000",
              # only report a solution once
              "A < B",
              "B < C", 
              "C < D", 
            ],
            answer="(A, B, C, D)",
            env=dict(mini=mini, maxi=maxi), # external functions
            digits=irange(1, 9),
        )
         
        # Solve and print answer
        p.run(verbose=16)
        

        And you could use Python’s argument syntax to deal with the list of digits without unpacking them:

        def mini(*ds):
          ...
          for s in subsets(ds, size=4, select="P"):
            ...
        

        Like

    • Frits's avatar

      Frits 3:21 pm on 16 September 2020 Permalink | Reply

      Thanks.

      I have seen the (*ds) before and have done some investigation but it is not yet in my “tool bag”.

      Like

  • Unknown's avatar

    Jim Randell 3:01 pm on 13 September 2020 Permalink | Reply
    Tags:   

    Teaser 2731: City snarl-up 

    From The Sunday Times, 25th January 2015 [link]

    I had to drive the six miles from my home into the city centre. The first mile was completed at a steady whole number of miles per hour (and not exceeding the 20mph speed limit). Then each succeeding mile was completed at a lower steady speed than the previous mile, again at a whole number of miles per hour.

    After two miles of the journey my average speed had been a whole number of miles per hour, and indeed the same was true after three miles, after four miles, after five miles, and at the end of my journey.

    How long did the journey take?

    [teaser2731]

     
    • Jim Randell's avatar

      Jim Randell 3:02 pm on 13 September 2020 Permalink | Reply

      My first program looked at all sequences of 6 decreasing speeds in the range 1 to 20 mph. It was short but took 474ms to run.

      But it’s not much more work to write a recursive program that checks the average speeds as it builds up the sequence.

      This Python 3 program runs in 50ms.

      Run: [ @repl.it ]

      from enigma import (Rational, irange, as_int, catch, printf)
      
      Q = Rational()  # select a rational implementation
      
      # check speeds for distance d, give a whole number average
      check = lambda d, vs: catch(as_int, Q(d, sum(Q(1, v) for v in vs)))
      
      # solve for k decreasing speeds, speed limit m
      def solve(k, m, vs=[]):
        n = len(vs)
        # are we done?
        if n == k:
          yield vs
        else:
          # add a new speed
          for v in irange(m, 1, step=-1):
            vs_ = vs + [v]
            if n < 1 or check(n + 1, vs_):
              yield from solve(k, v - 1, vs_)
      
      # find a set of 6 speeds, not exceeding 20mph
      for vs in solve(6, 20):
        # calculate journey time (= dist / avg speed)
        t = Q(6, check(6, vs))
        printf("speeds = {vs} -> time = {t} hours")
      

      Solution: The journey took 2 hours in total.

      The speeds for each mile are: 20mph, 12mph, 6mph, 5mph, 2mph, 1mph.

      Giving the following times for each mile:

      mile 1: 3 minutes
      mile 2: 5 minutes
      mile 3: 10 minutes
      mile 4: 12 minutes
      mile 5: 30 minutes
      mile 6: 60 minutes
      total: 120 minutes

      And the following overall average speeds:

      mile 1: 20 mph
      mile 2: 15 mph
      mile 3: 10 mph
      mile 4: 8 mph
      mile 5: 5 mph
      mile 6: 3 mph

      Like

    • Frits's avatar

      Frits 1:40 pm on 16 September 2020 Permalink | Reply

      With a decent elapsed time.

       
      from enigma import SubstitutedExpression 
      
      # is average speed a whole number
      def avg_int(li):
        miles = len(li)
        time = 0
        # Add times (1 mile / speed)
        for i in range(miles):
          time += 1 / li[i]
        #return miles % time == 0
        return (miles / time).is_integer()
      
      p = SubstitutedExpression([
          "AB <= 20",
          # no zero speeds allowed
          "KL > 0",
          # speeds are descending
          "AB > CD",
          "CD > EF",
          "EF > GH", 
          "GH > IJ",
          "IJ > KL",
          # average speeds must be whole numbers
          "avg_int([AB, CD])",
          "avg_int([AB, CD, EF])",
          "avg_int([AB, CD, EF, GH])",
          "avg_int([AB, CD, EF, GH, IJ])",
          "avg_int([AB, CD, EF, GH, IJ, KL])",
          ],
          verbose=0,
          answer="(AB, CD, EF, GH, IJ, KL, \
                  60/AB + 60/CD + 60/EF + 60/GH + 60/IJ + 60/KL)",
          env=dict(avg_int=avg_int), # external functions
          d2i="",            # allow number respresentations to start with 0
          distinct="",       # letters may have same values                     
      )
      
      # Solve and print answer
      for (_, ans) in p.solve(): 
        print("Speeds:", ", ".join(str(x) for x in ans[:-1]))
        print(f"Minutes: {round(ans[6])}")  
      
      # Output:
      #
      # Speeds: 20, 12, 6, 5, 2, 1
      # Minutes: 120
      

      @Jim, do you discourage the use of / for division?

      Is there a better way to check that a division by a float is a whole number?
      I tried divmod(p, r) but sometimes r is close to zero like x E-19.
      (miles % time == 0) also failed.

      Like

      • Jim Randell's avatar

        Jim Randell 2:39 pm on 16 September 2020 Permalink | Reply

        @Frits

        I am careful about my use of / for division, as it behaves differently in Python 2 and Python 3 (and I do generally still attempt to write code that works in both Python 2 and Python 3 – although the day when Python 2 is abandoned completely seems to be getting closer).

        But I do tend to avoid using float() objects unless I have to. Floating point numbers are only ever approximations to a real number, so you have to allow some tolerance when you compare them, and rounding errors can build up in complex expressions. (Python recently added math.isclose() to help with comparing floats).

        On the other hand, I am a big fan of the Python fractions module, which can represent rational numbers and operate on them to give exact answers. So if I can’t keep a problem within the integers (which Python also will represent exactly) I tend to use fraction.Fraction if possible.

        (The only problem is that it is a bit slower, but for applications that need more speed gmpy2.mpq() can be used, which gives a faster implementation of rationals. I might add a Rational() function to enigma.py to search for an appropriate rational implementation).

        Like

        • Jim Randell's avatar

          Jim Randell 4:46 pm on 16 September 2020 Permalink | Reply

          I have added code to enigma.py to allow selecting of a class for rational numbers.

          So now instead of using:

          from fractions import Fraction as Q
          

          You can import the function Rational() from enigma.py and then use it to select a rational implementation:

          from enigma import Rational
          
          Q = Rational()  # or ...
          Q = Rational(verbose=1)
          

          Setting the verbose parameter will make it display which implementation is being used.

          I’ve got gmpy2 installed on my system and this change improved the runtime of my original code from 448ms (using fractions.Fraction under PyPy 7.3.1) to 153ms (using gmpy2.mpq under CPython 2.7.18).

          Like

  • Unknown's avatar

    Jim Randell 4:44 pm on 11 September 2020 Permalink | Reply
    Tags:   

    Teaser 3025: Please mind the gap 

    From The Sunday Times, 13th September 2020 [link] [link]

    Ann, Beth and Chad start running clockwise around a 400m running track. They run at a constant speed, starting at the same time and from the same point; ignore any extra distance run during overtaking.

    Ann is the slowest, running at a whole number speed below 10 m/s, with Beth running exactly 42% faster than Ann, and Chad running the fastest at an exact percentage faster than Ann (but less than twice her speed).

    After 4625 seconds, one runner is 85m clockwise around the track from another runner, who is in turn 85m clockwise around the track from the third runner.

    They decide to continue running until gaps of 90m separate them, irrespective of which order they are then in.

    For how long in total do they run (in seconds)?

    [teaser3025]

     
    • Jim Randell's avatar

      Jim Randell 5:28 pm on 11 September 2020 Permalink | Reply

      For the distances involved they must be very serious runners.

      I amused myself by writing a generic function to check the runners are evenly spaced. Although for the puzzle itself it is possible to use a simpler formulation that does not always produce the correct result. But once you’ve got that sorted out the rest of the puzzle is straightforward.

      This Python program runs in 55ms.

      Run: [ @replit ]

      from enigma import (irange, div, tuples, printf)
      
      # one lap of the track is 400m
      L = 400
      
      # time for separation of 85m
      T = 4625
      
      # check for equal separations
      def check_sep(ps, v):
        k = len(ps) - 1
        # calculate the remaining gap
        g = L - k * v
        if not (k > 0 and g > 0): return False
        # calculate positions of the runners
        ps = sorted(p % L for p in ps)
        # calculate the distances between them
        ds = list((b - a) % L for (a, b) in tuples(ps, 2, circular=1))
        # look for equal spacings
        return (g in ds and ds.count(v) >= k)
      
      # consider speeds for A
      for A in irange(1, 9):
        # A's distance after T seconds
        dA = A * T
        # B's distance after T seconds
        dB = div(dA * 142, 100)
        if dB is None: continue
        # A and B are separated by 85m or 170m
        if not (check_sep((dA, dB), 85) or check_sep((dA, dB), 170)): continue
      
        # now choose a whole number percentage increase on A
        for x in irange(143, 199):
          # C's distance after T seconds
          dC = div(dA * x, 100)
          if dC is None: continue
          # A, B, C are separated by 85m
          if not check_sep((dA, dB, dC), 85): continue
          printf("A={A} -> dA={dA} dB={dB}; x={x} dC={dC}")
      
          # continue until separation is 90m
          for t in irange(T + 1, 86400):
            dA = A * t
            dB = div(dA * 142, 100)
            dC = div(dA * x, 100)
            if dB is None or dC is None: continue
            if not check_sep((dA, dB, dC), 90): continue
            # output solution
            printf("-> t={t}; dA={dA} dB={dB} dC={dC}")
            break
      

      Solution: They run for 7250 seconds (= 2 hours, 50 seconds).

      After which time A will have covered 29 km (about 18 miles), B will have covered 41.2 km (about 25.6 miles), and C (who runs at a speed 161% that of A) will have covered 46.7 km (about 29 miles), which is pretty impressive for just over 2 hours.

      For comparison, Mo Farah on his recent world record breaking run of 21,330 m in 1 hour [link], would not have been able to keep up with C (who maintained a faster pace for just over 2 hours), and would be only slightly ahead of B at the 1 hour mark.

      Like

  • Unknown's avatar

    Jim Randell 9:18 am on 10 September 2020 Permalink | Reply
    Tags:   

    Teaser 2730: It’s a lottery 

    From The Sunday Times, 18th January 2015 [link]

    I regularly entered the Lottery, choosing six numbers from 1 to 49. Often some of the numbers drawn were mine but with their digits in reverse order. So I now make two entries: the first entry consists of six two-figure numbers with no zeros involved, and the second entry consists of six entirely different numbers formed by reversing the numbers in the first entry. Interestingly, the sum of the six numbers in each entry is the same, and each entry contains just two consecutive numbers.

    What (in increasing order) are the six numbers in the entry that contains the highest number?

    [teaser2730]

     
    • Jim Randell's avatar

      Jim Randell 9:18 am on 10 September 2020 Permalink | Reply

      Each digit in the 2-digit numbers must form a tens digit of one of the 2-digit lottery numbers, so the digits are restricted to 1, 2, 3, 4, and no number may use two copies of the same digit.

      The following Python program runs in 51ms.

      Run: [ @replit ]

      from enigma import (subsets, irange, intersect, tuples, printf)
      
      # generate (number, reverse) pairs
      ps = list((10 * a + b, 10 * b + a) for (a, b) in subsets(irange(1, 4), size=2, select="P"))
      
      # count consecutive pairs of numbers
      cons = lambda s: sum(y == x + 1 for (x, y) in tuples(s, 2))
      
      # find 6-sets of pairs
      for ss in subsets(ps, size=6):
        # split the pairs into numbers, and reverse numbers
        (ns, rs) = zip(*ss)
        rs = sorted(rs)
        # ns has the highest number
        if not (ns[-1] > rs[-1]): continue
        # sequences have the same sum
        if sum(ns) != sum(rs): continue
        # sequences have no numbers in common
        if intersect((ns, rs)): continue
        # sequences have exactly one consecutive pair
        if not (cons(ns) == 1 and cons(rs) == 1): continue
        # output solution
        printf("{ns}; {rs}", rs=tuple(rs))
      

      Solution: The six numbers are: 13, 21, 23, 24, 41, 43.

      23 and 24 are consecutive.

      Which means the reversed numbers (in order) are: 12, 14, 31, 32, 34, 42.

      31 and 32 are consecutive.

      Like

      • Frits's avatar

        Frits 6:11 pm on 10 September 2020 Permalink | Reply

        As all 12 numbers must be different we can reduce the main loop from 924 to 64 iterations.
        We can’t pick more than one item from each of the 6 groups.

        There probably is a more elegant way to create the list sixgroups.

        Using function seq_all_different instead of intersect doesn’t seem to matter.

         
        from enigma import subsets, irange, printf, seq_all_different
        from itertools import product
        
        # group 1:  (12, 21) (21, 12)
        # group 2:  (13, 31) (31, 13)
        # group 3:  (14, 41) (41, 14)
        # group 4:  (23, 32) (32, 23)
        # group 5:  (24, 42) (42, 24)
        # group 6:  (34, 43) (43, 34)
        
        sixgroups = [[]]*6
        i = 0
        for a in range(1,4):
          for b in range(a+1,5):
            sixgroups[i] = [((10 * a + b, 10 * b + a))]
            sixgroups[i].append((10 * b + a, 10 * a + b))
            i += 1
        
        # pick one from each group
        sel = [p for p in product(*sixgroups)]
        
        # count consecutive pairs of numbers
        cons = lambda s: sum(y == x + 1 for (x, y) in list(zip(s, s[1:])))
         
        # find 6-sets of pairs
        for ss in sel:
          # split the pairs into numbers, and reverse numbers
          (ns, rs) = zip(*ss)
          ns = sorted(ns)
          rs = sorted(rs)
          # ns has the highest number
          if not(ns[-1] > rs[-1]): continue
          # sequences have the same sum
          if sum(ns) != sum(rs): continue
          # sequences have no numbers in common
          if not seq_all_different(ns + rs): continue
          # sequences have exactly one consective pair
          if not(cons(ns) == 1 and cons(rs) == 1): continue
          # output solution
          printf("{ns}; {rs}", rs=tuple(rs))
        

        Like

        • Jim Randell's avatar

          Jim Randell 9:25 pm on 10 September 2020 Permalink | Reply

          For this particular puzzle (where all 12 possible numbers are used) we can go down to 32 pairs of sequences, as we always need to put the largest number (43) into the first sequence (and so 34 goes in the second sequence, and we don’t need to check the sequences have no numbers in common).

          Here’s my way of dividing the 12 candidate digit pairs into the 32 pairs of sequences:

          from enigma import (subsets, irange, nconcat, tuples, printf)
          
          # possible digit pairs
          ps = list(subsets(irange(1, 4), size=2))
          
          # construct numbers from digit pairs <ps> and flags <fs> (and xor flag <x>)
          def _construct(ps, fs, x=0):
            for ((a, b), f) in zip(ps, fs):
              yield (nconcat(a, b) if f ^ x else nconcat(b, a))
          construct = lambda *args: sorted(_construct(*args))
          
          # count consecutive pairs of numbers
          cons = lambda s: sum(y == x + 1 for (x, y) in tuples(s, 2))
          
          # choose an order to assemble digits
          for fs in subsets((0, 1), size=5, select="M"):
            fs += (0,)
            ns = construct(ps, fs, 0)
            rs = construct(ps, fs, 1)
            # sequences have the same sum
            if sum(ns) != sum(rs): continue
            # sequences have exactly one consecutive pair
            if not (cons(ns) == 1 and cons(rs) == 1): continue
            # output solution
            printf("{ns}; {rs}")
          

          And as all the numbers are used, and their sum is 330, we know each of the sequences must sum to 165.

          The more analysis we do, the less work there is for a program to do.

          Like

          • Frits's avatar

            Frits 5:11 pm on 11 September 2020 Permalink | Reply

            We can go on like this.

            fi, three consecutive numbers, we can exclude 111…, 000… and ..0.00 from fs and get it down from 34 to 18.

            12 13 14 23 24 34 Group A
            21 31 41 32 42 43 Group B
            -----------------
             9 18 27  9 18  9 Difference 
            

            Regarding the sum constraint we can derive that for each lottery entry from each group 2, 3 or 4 numbers have to picked.
            The numbers picked from group B must have a total difference of 45 (same for the numbers picked from group A)..

            If only 2 numbers are picked from a group then this group must be group B and the numbers {41, 42} or {41, 31}.

            Like

    • Frits's avatar

      Frits 11:47 am on 10 September 2020 Permalink | Reply

      Based on Jim’s cons lambda function.

       
      from enigma import SubstitutedExpression, irange, seq_all_different, tuples
      
      p = SubstitutedExpression([
          # sum of the six numbers in each entry is the same
          "AB + CD + EF + GH + IJ + KL == BA + DC + FE + HG + JI + LK",
          # ascending range
          "AB < CD", "CD < EF", "EF < GH", "GH < IJ", "IJ < KL",
          # all different numbers
          "diff([AB, CD, EF, GH, IJ, KL, BA, DC, FE, HG, JI, LK])",
          # each entry contains just two consecutive numbers
          "consec([AB, CD, EF, GH, IJ, KL]) == 1",
          "consec([BA, DC, FE, HG, JI, LK]) == 1",
          # report entry that contains the highest number
          "max(AB, CD, EF, GH, IJ, KL) >= max(BA, DC, FE, HG, JI, LK)",
         ],
          verbose=0,
          answer="AB, CD, EF, GH, IJ, KL",
          code="diff = lambda x: seq_all_different(x); \
                consec = lambda s: sum(y == x + 1 \
                                   for (x, y) in tuples(sorted(s), 2))",
          distinct="",
          digits=irange(1,4)
      )
      
      # Print answers
      for (_, ans) in p.solve():
        print(ans)  
      
      # Output:
      #
      # (13, 21, 23, 24, 41, 43)
      

      Like

      • Frits's avatar

        Frits 12:16 pm on 10 September 2020 Permalink | Reply

        list(zip(s, s[1:])) is the same as tuples(s, 2)

        Like

c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel
Design a site like this with WordPress.com
Get started