Updates from Jim Randell Toggle Comment Threads | Keyboard Shortcuts

  • Unknown's avatar

    Jim Randell 9:45 am on 11 January 2022 Permalink | Reply
    Tags:   

    Brain-Teaser 903: Ding-dong 

    From The Sunday Times, 26th November 1978 [link]

    Today a great celebration will take place on Bells Island, for it is the Feast of Coincidus. On this island there is monastery and a nunnery. At regular intervals (a whole number of minutes) the monastery bell dongs once. The nunnery bell rings at regular intervals too (different from the intervals of the monastery’s bell, but also a whole number of minutes). So the island also regularly reverberates with a ding from the nunnery’s bell. The Feast of Coincidus takes place whenever the monastery’s dong and the nunnery’s ding occur at the same moment, and that is exactly what is due to happen at noon today.

    Between consecutive Feasts the dongs from the monastery and the dings from the nunnery occur alternately and, although the two noises only coincide on Feast days, they do occur a minute apart at some other times.

    When the bells coincided last time (at noon, a prime number of days ago) this whole island indulged in its usual orgy of eating and drinking.

    How many days ago was that?

    This puzzle is included in the book The Sunday Times Book of Brain-Teasers: Book 1 (1980). The puzzle text above is taken from the book.

    After this puzzle was published The Sunday Times was hit by industrial action, and the next issue was not published until 18th November 1979.

    [teaser903]

     
    • Jim Randell's avatar

      Jim Randell 9:47 am on 11 January 2022 Permalink | Reply

      If the shorter interval is i minutes, then, working forwards from the previous feast (= 0) the bell rings at (minutes):

      i, 2i, 3i, 4i, … ni

      And if the shorter interval is (i + x) minutes, then that bell rings at:

      (i + x), 2(i + x), 3(i + x), … (n − 1)(i + x)

      And the last 2 times coincide:

      ni = (n − 1)(i + x)
      i = (n − 1)x
      x = i / (n − 1)

      And there are times where the bells ring only 1 minute apart. As the bells are drifting apart at the beginning and together at the end, and their interval is a whole number of minutes, they must ring 1 minute apart immediately after and immediately before they coincide. i.e. x = 1 and n = i + 1

      So, the number of intervals for the shorter bell is 1 more than than the length of the interval in minutes.

      And in prime p days there are 1440p minutes, so we have:

      1440p = ni = (i + 1)i
      p = i(i + 1) / 1440

      So we need to find two consecutive integers, whose product is the product of a prime and 1440.

      Run: [ @replit ]

      from enigma import irange, inf, div, is_prime, printf
      
      for i in irange(1, inf):
        p = div(i * (i + 1), 1440)
        if p is not None and is_prime(p):
          printf("i={i} p={p}")
          break
      

      Solution: The last feast was 1439 days ago.

      So, almost 4 years ago.

      We have: i = p = 1439.

      Like

    • Hugh+Casement's avatar

      Hugh+Casement 1:15 pm on 11 January 2022 Permalink | Reply

      The periods are 24 hours for one and 23 hours 59 minutes for the other.

      Like

  • Unknown's avatar

    Jim Randell 4:40 pm on 7 January 2022 Permalink | Reply
    Tags:   

    Teaser 3094: There’s always next year 

    From The Sunday Times, 9th January 2022 [link] [link]

    George and Martha annually examine around 500 candidates (give or take 5%). It is board policy to pass about a third of the entrants but the precise recent percentage pass rates were as above.

    The number of entrants in each year up to 2021 was different as was the number of successful candidates. George told Martha of the number of entries for 2022 (different again) and Martha calculated that, if X were to be once again a whole number (also different again but within the above range), the total number of successful candidates over the five-year period would be a perfect square.

    How many entries are there for 2022 and how many successful candidates did Martha calculate for 2022?

    [teaser3094]

     
    • Jim Randell's avatar

      Jim Randell 5:08 pm on 7 January 2022 Permalink | Reply

      I considered total candidates for each year in the range [475, 525], and by allowing the (integer) percentages to be in the range [30, 36] I was able to find a unique solution.

      This Python program runs in 53ms.

      Run: [ @replit ]

      from enigma import (
        divc, divf, div, irange, cproduct, unzip,
        seq_all_different, is_square, printf
      )
      
      # given pass rates (percentages)
      rates = [30, 32, 35, 36]
      
      # find viable "<n> of <t>" pairs for percentages 30 - 36
      pairs = dict()
      for x in irange(30, 36):
        pairs[x] = list()
        for n in irange(divc(475 * x, 100), divf(525 * x, 100)):
          t = div(100 * n, x)
          if t is not None:
            pairs[x].append((n, t))
      
      # consider possible (n, t) pairs for the given years
      for nts in cproduct(pairs[x] for x in rates):
        (ns, ts) = unzip(nts)
        if not (seq_all_different(ns) and seq_all_different(ts)): continue
        nsum = sum(ns)
      
        # consider possible (n, t) pairs for 2022
        for (k, vs) in pairs.items():
          if k in rates: continue
          for (n, t) in vs:
            if n in ns or t in ts: continue
            # is the total number of n's a square?
            if is_square(n + nsum):
              printf("k={k}% -> {n} of {t} [ns={ns} ts={ts}]")
      

      Solution: There were 500 entries for 2022. Martha’s calculation was for 165 successful candidates.

      Like

    • GeoffR's avatar

      GeoffR 8:29 pm on 7 January 2022 Permalink | Reply

      % A Solution in MiniZinc
      include "globals.mzn";
      
      predicate is_sq(var int: y) =
      exists(z in 1..ceil(sqrt(int2float(ub(y))))) (z*z = y );
      
      % Total entrants for each year & given pass rates
      var 475..525:Y2018;  %Pass % = 30
      var 475..525:Y2019;  %Pass % = 32
      var 475..525:Y2020;  %Pass % = 35
      var 475..525:Y2021;  %Pass % = 36
      
      var 475..525:Y2022;  
      var 30..36:P5;  % Per Cent pass rate for Y2022
      
      % total entrants, successful candidates, pass rates are all different
      constraint all_different( [Y2018, Y2019, Y2020, Y2021, Y2022]);
      constraint all_different ([SC2018, SC2019, SC2020, SC2021, SC2022]);
      constraint all_different([30, 32, 35, 36, P5]);
      
      % Total passes for each year
      % LB = 0.3 * 475 = 142, UB = 0.36 * 525 = 189
      var 142..189:SC2018; var 142..189:SC2019; var 142..189:SC2020;
      var 142..189:SC2021; var 142..189:SC2022;
      
      % calculate successful candidates for each year
      constraint 100 * SC2018 == 30 * Y2018;
      constraint 100 * SC2019 == 32 * Y2019;
      constraint 100 * SC2020 == 35 * Y2020;
      constraint 100 * SC2021 == 36 * Y2021;
      constraint 100 * SC2022 == P5 * Y2022;
      
      % total successful candidates for years (2018 - 2022) is a square
      constraint is_sq(SC2018 + SC2019 + SC2020 + SC2021 + SC2022);
      
      solve satisfy;
      
      output [ "Successful candidates for 2022 = " ++ show(SC2022) ++ "\n"
      ++ "Total entrants for 2022 = " ++ show(Y2022) 
      ++ "\n"  ++ "2022 Pass % = " ++ show(P5)];
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 9:09 am on 6 January 2022 Permalink | Reply
    Tags: by: David Preston   

    Brain-Teaser 896: Handshaking numbers 

    From The Sunday Times, 8th October 1978 [link]

    My wife and I attended a formal dinner at which there were just eight other people, namely the four couples Mr and Mrs Ailsa, Mr and Mrs Blackler, Mr and Mrs Caroline and Mr and Mrs Duncan. Introductions were made, and a certain number of handshakes took place (but, of course, no one shook hands with him/herself, nor with his/her spouse, nor more than once with anyone else). At the end of the evening I asked each other person how many hands they had shaken, and I was surprised to find that all the answers given were different. Also, the total of the number of handshakes made by the other four men was the same as the total of handshakes made by all five women.

    The only woman I shook hands with was my old friend Mrs Ailsa. We had a long chat and then I took her to one side and, being a jealous fellow, I asked her whose hands my wife had shaken. She was unable to tell me, but luckily I was able to work it out later from the above information.

    Whose hands did my wife shake? How many hands did Mrs Ailsa shake?

    This puzzle is included in the book The Sunday Times Book of Brain-Teasers: Book 1 (1980). The puzzle text above is taken from the book.

    [teaser896]

     
    • Jim Randell's avatar

      Jim Randell 9:11 am on 6 January 2022 Permalink | Reply

      This one is quite fun to solve manually.

      The largest possible number of handshaking partners is 8 (if you shake hands with everyone except yourself and your spouse).

      So the setter must have got the responses 0 – 8, when he asked the other 9 people their numbers of handshakes.

      Programatically I used a MiniZinc model to construct the handshaking matrix, and then formatted the output using my minizinc.py wrapper.

      The following Python 3 program runs in 207ms.

      from enigma import join, printf
      from minizinc import MiniZinc
      
      # we label the people in pars (1, 2) (3, 4) ... (9, 10)
      people = ["Mr S", "Mrs S", "Mr A", "Mrs A", "Mr B", "Mrs B", "Mr C", "Mrs C", "Mr D", "Mrs D"]
      # map people to integers, and integers to people
      p2i = dict((x, i) for (i, x) in enumerate(people, start=1))
      i2p = dict((v, k) for (k, v) in p2i.items())
      
      ps2is = lambda ps: join((p2i[p] for p in ps), sep=", ", enc="{}")
      MrS = p2i["Mr S"]
      MrABCD = ps2is("Mr " + x for x in "ABCD")
      MrsSABCD = ps2is("Mrs " + x for x in "SABCD")
      
      # construct the MiniZinc model
      model = f"""
      include "globals.mzn";
      
      set of int: People = 1..10;
      
      % boolean handshake matrix
      array [People, People] of var 0..1: x;
      
      % handshakes are reciprocal
      constraint forall (i, j in People) (x[i, j] = x[j, i]);
      
      % no-one shakes hands with themselves
      constraint forall (i in People) (x[i, i] = 0);
      
      % no-one shakes hands with their spouse
      constraint forall (i in People where i mod 2 = 1) (x[i, i + 1] = 0);
      constraint forall (i in People where i mod 2 = 0) (x[i, i - 1] = 0);
      
      % total number of handshakes
      array [People] of var 0..8: t;
      constraint forall (i in People) (t[i] = sum (j in People) (x[i, j]));
      
      % apart from Mr S, everyone had a different total
      constraint all_different([t[i] | i in People where i != {MrS}]);
      
      % total for Mr A, B, C, D = total for Mrs S, A, B, C, D
      constraint sum ([t[i] | i in {MrABCD}]) = sum ([t[i] | i in {MrsSABCD}]);
      
      % Mr S shook hands with Mrs A, but no other wives
      constraint x[{MrS}, {p2i["Mrs A"]}] = 1;
      constraint x[{MrS}, {p2i["Mrs B"]}] = 0;
      constraint x[{MrS}, {p2i["Mrs C"]}] = 0;
      constraint x[{MrS}, {p2i["Mrs D"]}] = 0;
      
      % eliminate duplicates by placing an order on Mr B, C, D
      constraint increasing([t[{p2i["Mr B"]}], t[{p2i["Mr C"]}], t[{p2i["Mr D"]}]]);
      
      solve satisfy;
      """
      
      # solve the model
      for s in MiniZinc(model).solve():
        # output the handshakes
        x = s['x']
        for k in sorted(x.keys()):
          v = list(k_ for k_ in x[k].keys() if x[k][k_] == 1)
          printf("{k} [{n}] = ({v})", k=i2p[k], v=join((i2p[i] for i in v), sep=", "), n=len(v))
        printf()
      

      Solution: The setters wife (Mrs S) shook hands with: Mrs A, Mr B, Mr C, Mr D; Mrs A shook hands with 8 others.


      Manually:

      We have “Mr S” and the other 8 who participated in 0 – 8 handshakes, one value each.

      “0” can’t shake hands with anybody, and “8” can’t shake hands with “0”, so must shake hands with everyone else (and so must be married to “0”).

      Filling in the handshakes we know:

      Mr S: 8, …
      0: none (complete, married to 8)
      1: 8 (complete)
      2: 8, …
      3: 8, …
      4: 8, …
      5: 8, …
      6: 8, …
      7: 8, …
      8: Mr S, 1, 2, 3, 4, 5, 6, 7 (complete, married to 0)

      Now “7”, can’t shake hands with “0”, “1” or “8”, so must shake hands with everyone else (and must be married to “1”). And this completes “7” and “2”. Similarly we complete “6” and “3” (and “6” must be married to “2”), then “5” and “4” (“5” is married to “3”):

      Mr S: 5, 6, 7, 8
      0: none (complete, married to 8)
      1: 8 (complete, married to 7)
      2: 7, 8 (complete, married to 6)
      3: 6, 7, 8 (complete, married to 5)
      4: 5, 6, 7, 8 (complete)
      5: Mr S, 4, 6, 7, 8 (complete, married to 3)
      6: Mr S, 3, 4, 5, 7, 8 (complete, married to 2)
      7: Mr S, 2, 3, 4, 5, 6, 8 (complete, married to 1)
      8: Mr S, 1, 2, 3, 4, 5, 6, 7 (complete, married to 0)

      So “0” – “8” are complete, and hence so is “Mr S”, and he must be married to “4” (“Mrs S”).

      And Mr S shook hands with just one woman (Mrs A), so three of 5, 6, 7, 8 must be men (and the other one is Mrs A).

      We know the sum of the handshakes of the 5 wives must sum to half of sum(0, 1, 2, …, 8) = 36, i.e. 18. And Mrs S is “4”.

      So we need the remaining 4 wives (one each from (0, 8) (1, 7) (2, 6) (3, 5)) to sum to 14.

      The only possibilities are 0 + 7 + 2 + 5 = 14, and 8 + 1 + 2 + 3 = 14.

      The first is ruled out as 5 and 7 can’t both be wives (Mr S only shook hands with one woman).

      So the wives are 1, 2, 3, 8 (and 4). And the corresponding husbands are 7, 6, 5, 0 (and Mr S).

      Hence: “8” = “Mrs A”; “0” = “Mr A”.

      And Mr B, C, D not distinguishable in the puzzle so we can order them by the number of handshakes (the other arrangements will give further solutions), so we can now complete the matrix:

      (4) Mr S: Mr B, Mr C, Mr D, Mrs A
      0 = Mr A: none
      1 = Mrs D: Mrs A
      2 = Mrs C: Mr D, Mrs A
      3 = Mrs B: Mr C, Mr D, Mrs A
      4 = Mrs S: Mr B, Mr C, Mr D, Mrs A
      5 = Mr B: Mr S, Mrs S, Mr C, Mr D, Mrs A
      6 = Mr C: Mr S, Mrs B, Mrs S, Mr B, Mr D, Mrs A
      7 = Mr D: Mr S, Mrs C, Mrs B, Mrs S, Mr B, Mr C, Mrs A
      8= Mrs A: Mr S, Mrs D, Mrs C, Mrs B, Mrs S, Mr B, Mr C, Mr D

      Like

    • NigelR's avatar

      NigelR 7:13 pm on 12 January 2022 Permalink | Reply

      I found it very much quicker to solve this puzzle manually than unentangle the code but the program below makes no assumptions about the underlying logic other than the sum of digits 0-8 being 36.
      I am thinking of using the nickname Thor since a big hammer seems to be my weapon of choice!!

      
      from itertools import combinations as comb,permutations as perm
      m=['am','bm','cm','dm'] #list of males not including setter
      f=['af','bf','cf','df','ef'] #list of females
      pairs=[['am','af'],['bm','bf'],['cm','cf'],['dm','df'],['em','ef']] #pairs of spouses
      
      #find combinations of digits where m and f both sum to 18
      def gen():
          for x in comb([0,1,2,3,4,5,6,7,8],4):
              if sum(x)!=18:continue
              y = [y for y in range(0,9) if y not in x]    
              for h in perm(x):
                  for w in perm(y):
                      yield  h+w
      #check allocations of shakes match 0-8 and setter shakes hands with Mrs A: :
      def test1():
          for i in mat:
              if len(mat[i])!=i:return False
          if 'em' not in mat[alloc['af']]: return False   
      #...and Mrs A is only female to shake setter's hand
          count=0
          for i in f:
              if 'em' in mat[alloc[i]]:count+=1
          if count >1:return False
          return True
      
      for seq in gen():    
          mat= {i:[] for i in range(0,9)}  # clear mat entries from previous iteration
          alloc= {i:j for (i,j) in zip(m+f,seq)} # set alloc to access attendees with current shake numbers
          point= {j:i for [i,j] in alloc.items()} #pointer - transpose of alloc to cross reference shake numbers and attendees
          
          for i in range(0,9):
             for j in range(i+1,9):
                  mat[j].append(point[8-i]) #populate mat  
      
          for i in mat:
              pair=[j for j in pairs if point[i] in j]
              mat[i] = [y for y in mat[i] if y not in [item for items in pair for item in items]]
              if len(mat[i])<i:mat[i].append('em')
          if not test1():continue
      #mat now contains valid set of handshakes for each attendee           
          for x in mat:
              print(point[x], 'shakes hand of',mat[x])
          break
      

      Like

  • Unknown's avatar

    Jim Randell 2:05 pm on 4 January 2022 Permalink | Reply
    Tags:   

    Teaser 2875: Easy as ABC 

    From The Sunday Times, 29th October 2017 [link] [link]

    I have ten cards and on each is one of the letters A, B, C, E, L, N, T, V, W and Y. On the back of each card is a different digit.

    The digits on T, E, N add to 10.

    The digits on T, W, E, L, V, E add to 12.

    The digits on T, W, E, N, T, Y add to 20.

    The digits on A, B, C add to …

    If I told you that last total, then you should be able to answer the following question:

    What are the digits on T, E and N respectively?

    [teaser2875]

     
    • Jim Randell's avatar

      Jim Randell 2:06 pm on 4 January 2022 Permalink | Reply

      Presumably we are to find the unique answer to the final question.

      The values of A, B, C are independent of the rest of the puzzle, and we are only interested in their sum, so we can place an ordering on them (and the remaining permutations would provide further solutions).

      I used the [[ SubstitutedExpression() ]] solver from the enigma.py library to find possible values of A + B + C and (T, E, N), and the used the [[ filter_unique() ]] function to find sums that give a unique value for (T, E, N).

      The following Python program runs in 60ms.

      Run: [ @replit ]

      from enigma import (SubstitutedExpression, filter_unique, uniq, unpack, printf)
      
      # find solutions to the given sums
      p = SubstitutedExpression(
        [
          "sum([T, E, N]) = 10",
          "sum([T, W, E, L, V, E]) = 12",
          "sum([T, W, E, N, T, Y]) = 20",
          "A < B < C", # to remove duplicate solutions
        ],
        answer="(A + B + C, (T, E, N))",
        verbose=0,
      )
      
      # find solutions where A + B + C uniquely identifies (T, E, N)
      ss = filter_unique(
        uniq(ans for (d, ans) in p.solve()),
        unpack(lambda ABC, TEN: ABC),
        unpack(lambda ABC, TEN: TEN),
      ).unique
      
      # output solutions
      for (ABC, TEN) in ss:
        printf("A + B + C = {ABC} -> (T, E, N) = {TEN}") 
      

      Solution: T = 3; E = 2; N = 5.

      The complete set of values:

      {A, B, C} = {7, 8, 9}
      {L, V} = {0, 4}
      E = 2
      N = 5
      T = 3
      W = 1
      Y = 6

      Like

    • GeoffR's avatar

      GeoffR 6:38 pm on 4 January 2022 Permalink | Reply

      The only way I could find a unique solution for (T,E,N) in MiniZinc was to maximise the sum of (A+B+C). Other potential values of (T,E,N) were found, but they were not unique.

      
      % A Solution in MiniZinc
      include "globals.mzn";
      
      var 0..9:A; var 0..9:B; var 0..9:C; var 0..9:E;
      var 0..9:L; var 0..9:N; var 0..9:T; var 0..9:V;
      var 0..9:W; var 0..9:Y;
      
      constraint all_different([A, B, C, E, L, N, T, V, W, Y]);
      constraint T > 0;
      
      constraint T + E + N == 10;
      constraint T + W + E + L + V + E == 12;
      constraint T + W + E + N + T + Y == 20;
      
      solve maximize(A + B + C);
      
      output["[A + B + C] = " ++ show(A + B + C) ++ 
      ", [T,E,N] = " ++ show([T,E,N]) ];
      
      % [A + B + C] = 17, [T,E,N] = [1, 0, 9]
      % ----------
      % [A + B + C] = 18, [T,E,N] = [2, 0, 8]
      % ----------
      % [A + B + C] = 20, [T,E,N] = [2, 0, 8]
      % ----------
      % [A + B + C] = 22, [T,E,N] = [2, 0, 8]
      % ----------
      % [A + B + C] = 23, [T,E,N] = [1, 2, 7]
      % ----------
      % [A + B + C] = 24, [T,E,N] = [3, 2, 5] <<< Solution with unique values of  A, B and C.
      % ----------
      % ==========
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 11:37 am on 2 January 2022 Permalink | Reply
    Tags:   

    An American Brain Teaser 

    From The Sunday Times, 5th June 1949 [link]

    The conundrum below below was said to have been posed by an American professor, with unflattering results, to an academic congress.

    A man calling on a friend in an American town saw a number of children playing in the garden. Without counting them he said to his host: “Surely they are not all yours?”. The other man replied: “No, there are four families, the largest being my own, the next largest my brother’s, the third largest my younger sister’s, and the smallest my elder sister’s. It is a pity that there are too few to make up a couple of base-ball teams”. (There are nine a side at base-ball).

    Then he added: “Oddly enough, the numbers of the four families of children, multiplied together, make the street number of this house”. The visitor, who knew the street number, thought for a moment and said: “Has the smallest family one or two children?”. His host having given the answer, he then stated with certainty how many there were in each family.

    How many were there?

    This one of the occasional Holiday Brain Teasers published in The Sunday Times prior to the start of numbered Teasers in 1961 that I have found. A prize of 10 guineas was offered.

    [teaser-1949-06-05] [teaser-unnumbered]

     
    • Jim Randell's avatar

      Jim Randell 11:38 am on 2 January 2022 Permalink | Reply

      This Python program runs in 51ms.

      Run: [ @replit ]

      from enigma import (irange, decompose, group, multiply, unpack, printf)
      
      # generate possible arrangements
      def generate():
        # consider the total number of children (< 18)
        for t in irange(10, 17):
          # break the total down into 4 families
          for ns in decompose(t, 4):
            yield ns
      
      # group the arrangements by product
      g = group(generate(), by=multiply)
      
      # consider products, and arrangements that make that product
      for (k, vs) in g.items():
        # there must be more than 1 arrangement
        if not (len(vs) > 1): continue
        # now group the arrangements by the smallest value ...
        g1 = group(vs, unpack(lambda a, b, c, d: a))
        # ... which must be 1 or 2
        if not (set(g1.keys()) == {1, 2}): continue
        # and find unique groups
        for (a, ns) in g1.items():
          if len(ns) == 1:
            printf("kids = {ns[0]}; k={k} vs={vs}")
      

      Solution: The numbers of children in the families were: 2, 3, 4, 5.


      The house number is 120, so the possible numbers of children are:

      (1, 3, 5, 8)
      (1, 4, 5, 6)
      (2, 3, 4, 5)

      The response for the number of children in the smallest family must be “2” (as “1” would not allow the numbers to be deduced), and this leads to a single arrangement.

      Like

    • GeoffR's avatar

      GeoffR 4:39 pm on 2 January 2022 Permalink | Reply

      % A Solution in MiniZinc
      % Look for three solutions - ref Jim's posting
      include "globals.mzn";
      
      int: total == 18; % max sum of ages < total
      var 24..360: num; % max UB = 3*4*5*6
      
      % Three solutions for 4 children
      var 1..10:a; var 1..10:b; var 1..10:c; var 1..10:d; 
      var 1..10:e; var 1..10:f; var 1..10:g; var 1..10:h; 
      var 1..10:i; var 1..10:j; var 1..10:k; var 1..10:m; 
      
      constraint all_different([a, b, c, d]);
      constraint all_different([e, f, g, h]);
      constraint all_different([i, j, k, m]);
      
      % max total ages for four children
      constraint a + b + c + d < total /\ e + f + g + h < total
       /\ i + j + k + m < total;
       
      % the smallest family has one or two children
      constraint a == 1 \/ a == 2;
      constraint e == 1 \/ e == 2;
      constraint i == 1 \/ i == 2;
      constraint a != e /\ a != i;
       
      % make (a,b,c,d) the smallest family - one or two children
      constraint (a + b + c + d) < (e + f + g + h) 
      /\ (e + f + g + h) < (i + j + k + m);
      
      % the street number of the house
      constraint num == a * b * c * d /\ num == e * f * g * h 
      /\ num == i * j * k * m;
      
      % put children's ages in order
      constraint increasing([a, b, c, d]) /\  increasing([e, f, g, h])
      /\ increasing ([i, j, k, m]);
      
      solve satisfy;
      
      output["House number = " ++ show(num) ++ "\n"
      ++ " Family children(1) = " ++ show([a, b, c, d]) ++ "\n"
      ++ " Family children(2) = " ++ show([e, f, g, h]) ++ "\n"
      ++ " Family children(3) = " ++ show([i, j, k, m]) ++ "\n" ];
      
      % House number = 120
      %  Family children(1) = [2, 3, 4, 5]  <<< Solution
      %  Family children(2) = [1, 4, 5, 6]
      %  Family children(3) = [1, 3, 5, 8]
      % ----------
      % ==========
      
      
      

      Like

  • Unknown's avatar

    Jim Randell 3:56 pm on 30 December 2021 Permalink | Reply
    Tags:   

    Teaser 3093: Shout snap! 

    From The Sunday Times, 2nd January 2022 [link] [link]

    My grandson and I play a simple card game. We have a set of fifteen cards on each of which is one of the words ACE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, SHOUT and SNAP. We shuffle the cards and then display them one at a time. Whenever two consecutive cards have a letter of the alphabet occurring on both we race to shout “Snap!”. In a recent game there were no snaps. I counted the numbers of cards between the “picture-cards” (J, Q, K) and there was the same number between the first and second picture-cards occurring as between the second and third. Also, the odd-numbered cards (3, 5, 7, 9) appeared in increasing order during the game.

    In order, what were the first six cards?

    [teaser3093]

     
    • Jim Randell's avatar

      Jim Randell 4:48 pm on 30 December 2021 Permalink | Reply

      The following Python 3 program runs in 478ms.

      Run: [ @replit ]

      from enigma import subsets, intersect, join, printf
      
      # the cards
      cards = "ACE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING SHOUT SNAP".split()
      
      # which cards snap?
      snap = set()
      for (x, y) in subsets(cards, size=2):
        if intersect([x, y]):
          snap.update([(x, y), (y, x)])
      
      # generate sequences with no snaps
      def generate(cards, xs=[], pics=[], subseq=None):
        # are we done?
        if not cards:
          yield xs
        else:
          # choose the next card
          for (i, x) in enumerate(cards):
            if xs and (x, xs[-1]) in snap: continue
      
            # check subsequence cards appear in order
            ss = subseq
            if x in subseq:
              if x != subseq[0]: continue
              ss = ss[1:]
      
            # check picture cards appear equally distanced
            ps = pics
            if x in {'JACK', 'QUEEN', 'KING'}:
              ps = ps + [len(xs)]
              if len(ps) == 3 and ps[2] - ps[1] != ps[1] - ps[0]: continue
      
            # solve for the remaining cards
            yield from generate(cards[:i] + cards[i + 1:], xs + [x], ps, ss)
      
      # find solutions
      for ss in generate(cards, subseq=['THREE', 'FIVE', 'SEVEN', 'NINE']):  
        printf("{ss}", ss=join(ss, sep=" "))
      

      Solution: The first six cards were: EIGHT, SNAP, THREE, KING, ACE, SHOUT.

      And the full sequence is:

      EIGHT, SNAP, THREE, KING, ACE, SHOUT, FIVE, TWO, QUEEN, SIX, TEN, FOUR, SEVEN, JACK, NINE

      There are 4 cards between KING and QUEEN, and 4 cards between QUEEN and JACK.

      Like

      • NigelR's avatar

        NigelR 3:50 pm on 31 December 2021 Permalink | Reply

        A typical brute force approach from me. It is neither pretty nor quick, but it gets the job done (eventually!). I could probably have mined a bitcoin using less processing effort.

        
        # STBT 3093
        
        from itertools import permutations as perm
        
        cards=['ACE','TWO','THREE','FOUR','FIVE','SIX', 'SEVEN', 'EIGHT', 'NINE', 'TEN', 'JACK', 'QUEEN', 'KING','SHOUT','SNAP']
        oddnums=['THREE','FIVE','SEVEN','NINE']
        odds=[]
        evens=[]
        
        def oddtest(self): #test self for numbers 3-9 in correct sequence
            ind = [self.index(z) for z in oddnums]
            for z in range(0,3):
                if ind[z]>ind[z+1]:return False
            return True 
        
        def pictest(): #test picture cards for consistent spacing
            j,q,k=seq.index('JACK'),seq.index('QUEEN'),seq.index('KING')
            if q<j and q<k:return False #Q must be between J & K for equal spacing since q is an even and other two are odds
            if q>j and q>k:return False
            if abs(q-j)!=abs(k-q): return False  #check for equal spacing
            return True 
        
        def seqtest(): #test seq for no shared letters in adjacent cards
            for i in range(0,14):
                for z in seq[i]:
                    if z in seq[i+1]:return False
            return True
        
        seq=cards
        evens=[x for x in cards if 'E' in x] # there are 8 cards with letter E, so can only be placed on even slots to avoid adjacency
        odds=[x for x in cards if x not in evens]
        
        for x in list(perm(evens)):
            if not oddtest(x): continue
            for y in list(perm(odds)):
                for i in range(0,8): seq[i*2]=x[i]
                for i in range(1,8): seq[(2*i)-1]=y[i-1]
                if not pictest():continue
                if not seqtest():continue
                print ('The first six cards drawn in order were:',seq[0:6])
        
        

        Like

        • Jim Randell's avatar

          Jim Randell 10:54 am on 2 January 2022 Permalink | Reply

          My first program was quite slow too. I generated all sequences without a “snap” and then applied the remaining conditions.

          To improve the speed I moved the conditions inside the [[ generate() ]] function, and that got the code down to running in less than a second.

          Your observation that there are 8 cards with an E, and 7 cards without (so they must be interleaved, starting with an E), speeds up my code to 287ms.

          We replace line 20 in my program with:

                if xs:
                  # can't snap with the previous card
                  if (x, xs[-1]) in snap: continue
                else:
                  # first card must have an E
                  if not ('E' in x): continue
          

          Like

          • Brian Gladman's avatar

            Brian Gladman 4:37 pm on 4 January 2022 Permalink | Reply

            @Jim I went down exactly the same path and arrived at a close to identical solution to your own.

            I missed the significance of cards with ‘E’s until it was pointed out here and this provides a major improvement in performance.

            If I add this to your version after line 18:

                pos_even = not (len(xs) & 1)
            

            and this after line 20:

                  if pos_even and 'E' not in x: continue
            

            the run time for me (using profile )drops by a factor of over 20.

            Like

          • Jim Randell's avatar

            Jim Randell 9:51 pm on 4 January 2022 Permalink | Reply

            Using the observation that the “with E” and “without E” sets of cards must be interleaved allows us to go back to the simpler approach where we generate (interleaved) sets of cards, and then check them for the remaining conditions, and still have the program run in a short time.

            from enigma import (cproduct, intersect, filter2, join, printf)
            
            # the cards
            cards = "ACE TWO THREE FOUR FIVE SIX SEVEN EIGHT NINE TEN JACK QUEEN KING SHOUT SNAP".split()
            
            # partition the cards into 2 sets
            (cs1, cs2) = filter2((lambda x: 'E' in x), cards)
            assert len(cs1) == len(cs2) + 1
            
            # which cards snap?
            snap = set()
            for (x, y) in cproduct([cs1, cs2]):
              if intersect([x, y]):
                snap.update([(x, y), (y, x)])
            
            # generate sequences with no snaps, interleaving cs1 and cs2
            def generate(cs1, cs2, xs=[]):
              # are we done?
              if not cs1:
                yield xs
              else:
                # choose the next card
                for (i, x) in enumerate(cs1):
                  if xs and (x, xs[-1]) in snap: continue
                  # solve for remaining cards
                  yield from generate(cs2, cs1[:i] + cs1[i + 1:], xs + [x])
            
            # find solutions
            for ss in generate(cs1, cs2):
              pos = lambda x: ss.index(x)
              # check THREE, FIVE, SEVEN, NINE appear in order
              if not (pos('THREE') < pos('FIVE') < pos('SEVEN') < pos('NINE')): continue
              # check JACK, QUEEN, KING are evenly spaced
              (i, j, k) = sorted(pos(x) for x in ['JACK', 'QUEEN', 'KING'])
              if not (j - i == k - j): continue
              # output solution
              printf("{ss}", ss=join(ss, sep=" "))
            

            Like

  • Unknown's avatar

    Jim Randell 10:23 am on 30 December 2021 Permalink | Reply
    Tags:   

    Teaser 2855: Fab four 

    From The Sunday Times, 11th June 2017 [link] [link]

    Here are four numbers, where each is the same fixed whole-number multiple of the previous one. However, in some places I have consistently replaced digits by letters — and in the other places the digits have been replaced by [asterisks]. In this way the numbers have become the fabulous four:

    JOHN
    P*UL
    R***O
    ****GE

    What number is my GROUP?

    [teaser2855]

     
    • Jim Randell's avatar

      Jim Randell 10:24 am on 30 December 2021 Permalink | Reply

      I used the [[ SubstitutedExpression ]] solver from the enigma.py library to solve this puzzle.

      I added lower case letters (which don’t have to be distinct from each other) to fill in the gaps in the words.

      The following run file executes in 83ms.

      Run: [ @replit ]

      #! python3 -m enigma -rr
      
      SubstitutedExpression
      
      --distinct="EGHJLNOPRU"
      --reorder=0
      
      "{JOHN} * {z} = {PaUL}"
      "{PaUL} * {z} = {RingO}"
      "{RingO} * {z} = {jeorGE}"
      
      --answer="{GROUP}"
      

      Solution: GROUP = 57209.

      The expressions are:

      1238 × 8 = 9904
      9904 × 8 = 79232
      79232 × 8 = 633856

      alphametically:

      JOHN × N = PPUL
      PPUL × N = RPOHO
      RPOHO × N = EHHNGE

      Like

  • Unknown's avatar

    Jim Randell 10:03 am on 28 December 2021 Permalink | Reply
    Tags:   

    Brain-Teaser 894: Prime consideration 

    From The Sunday Times, 24th September 1978 [link]

    At our local the other night I made the acquaintance of a chap called Michael and his wife Noelle. We talked a good bit about our respective families, our activities and our hobbies. When I happened to mention my interest in mathematical puzzles to Michael he said that he knew one at first hand which might give me some amusement. He proceeded to tell me that although he himself, his parents (who were born in different years), Noelle and their children (featuring no twins, triplets, etc.) had all been born in the nineteen-hundreds and none of them in a leap year, the numerical relationship between their years of birth was nevertheless in two respects a bit unusual.

    “In the first place”, he said, “just one of us has our year of birth precisely equal to the mean of all the others’ years of birth. But more remarkably the difference between my father’s year of birth and that of any one of the rest of us is a prime, and the same is true of that of my mother. And she, like Noelle here, had no child after she had passed her twenties”.

    And then with a grin he concluded, “So now you’ll know about the whole family and even, if you want, be able to figure out just how old Noelle is without having to be rude and ask her!”

    In which year was Noelle born? And how many children does she have?

    This puzzle is included in the book The Sunday Times Book of Brain-Teasers: Book 1 (1980). The puzzle text above is taken from the book.

    [teaser894]

     
    • Jim Randell's avatar

      Jim Randell 10:03 am on 28 December 2021 Permalink | Reply

      There are no multiple births for Noelle, but she could manage to have 2 children in a calendar year (by having one early in the year, and one late in the year).

      Also, if she was born at the end of the year (as is suggested by her name), it is possible to squeeze a child (or two) in during the calendar year containing her 30th birthday.

      In order to get a unique solution, we need to assume Michael and Noelle have more than 1 child (justified by his use of “children”).

      This Python program runs in 52ms.

      Run: [ @replit ]

      from enigma import (defaultdict, irange, Primes, subsets, div, printf)
      
      # check for leap years
      is_leap = lambda y: y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)
      
      # primes less than 100
      primes = Primes(100)
      
      # find possible 19xx years
      years = list(y for y in irange(1900, 1978) if not is_leap(y))
      
      # look for viable mother -> children maps
      kids = defaultdict(list)
      for (m, c) in subsets(years, size=2):
        k = c - m
        if 16 < k < 31:
          kids[m].append(c)
      
      # choose a year for M's mother
      for (MM, Ms) in kids.items():
        # all other years must have a prime difference to MM
        ys1 = set(y for y in years if abs(y - MM) in primes)
      
        # find a viable birth year for M
        for M in Ms:
          if not (M in ys1): continue
      
          # and for his father
          for MF in ys1:
            k = M - MF
            if not (k > 15 and k in primes): continue
            # all other years must also have a prime difference to MF
            ys2 = set(y for y in ys1 if abs(y - MF) in primes).difference([M, MF])
      
            # now find a year for N
            for N in ys2:
              ks = sorted(ys2.intersection(kids.get(N, [])))
              if not ks: continue
      
              # no multiple births, so (0, 1, 2) children in each year
              for ns in subsets((0, 1, 2), size=len(ks), select="M"):
                k = sum(ns)
                if k < 2: continue
                # ages
                ages = [MF, MM, M, N]
                for (n, v) in zip(ns, ks):
                  if n: ages.extend([v] * n)
                t = sum(ages)
                # exactly one of the birth years is the mean year
                m = div(t, len(ages))
                if m is None or ages.count(m) != 1: continue
      
                # output solution
                printf("MF={MF} MM={MM} -> M={M}; N={N} -> {k} kids; {ages} -> {m}")
      

      Solution: Noelle was born in 1943. She has 4 children.

      Michael’s father was born in 1900 (which was not a leap year), and his mother in 1902.

      Michael was born in 1931 (prime differences of 31 and 29 to his father and mother), and his mother was 28 or 29 when he was born.

      Noelle was born in 1943 (prime differences of 43 and 41 to Michael’s father and mother), towards the end of the year.

      Her four children were born in 1961 (one towards the beginning of the year, when Noelle was 17, and one towards the end of the year, when she was 17 or 18), and in 1973 (one towards the beginning of the year, when Noelle was 29, and one towards the end of the year, when she was still 29).

      Like

  • Unknown's avatar

    Jim Randell 9:14 am on 26 December 2021 Permalink | Reply
    Tags:   

    A Brain-Teaser: [Square convoy] 

    From The Sunday Times, 2nd January 1949 [link]

    Four ships in convoy are at the corners of a square with sides one mile long. Ship B is due north of A; C is due east of B, and D is due south of C. The four ships are each sailing north at 10 miles per hour. A motor-boat, which travels at 26 miles per hour, starts at A, delivers a message to B, then to C, then to D, and finally returns to A. The distances between the ships are traversed by the shortest possible routes, and no allowance need be made for time taken in turning.

    How far does the convoy advance whilst the motor-boat is going round?

    This is earliest of the occasional Holiday Brain Teasers published in The Sunday Times prior to the start of numbered Teasers in 1961 that I have found. Prizes of 10 guineas and 5 guineas were awarded.

    This puzzle was originally published with no title.

    [teaser-1949-01-02] [teaser-unnumbered]

     
    • Jim Randell's avatar

      Jim Randell 9:16 am on 26 December 2021 Permalink | Reply

      (1) A to B:

      The position of the motorboat is given by: 26t

      And the position of B is given by: (1 + 10t)

      These coincide when:

      26t = 1 + 10t
      16t = 1
      t = 1/16

      (2) B to C:

      The motorboat travels along the hypotenuse of a right-angled triangle, a distance: 26t.

      And C travels along another side, a distance: 10t.

      The remaining side being of length 1.

      (26t)² = (10t)² + 1²
      676t² = 100t² + 1
      t² = 1/576
      t = 1/24

      (3) C to D:

      The motorboat’s position is: −26t.

      D’s position is: −1 + 10t.

      −26t = −1 + 10t
      t = 1/36

      (4) D to A:

      A mirror image of B to C.

      So the total time taken is:

      T = 1/16 + 1/24 + 1/36 + 1/24
      T = 25/144

      And the distance travelled by each boat in the fleet:

      D = 10T
      D = 125/72
      D = 1.736 miles
      D = 110000 inches = 1 mile, 1295 yards, 20 inches

      Solution: The distance travelled by the fleet was 1 mile, 1295 yards, 20 inches.

      Like

  • Unknown's avatar

    Jim Randell 5:53 pm on 23 December 2021 Permalink | Reply
    Tags: ,   

    Teaser 3092: A Christmas Carol 

    From The Sunday Times, 26th December 2021 [link] [link]

    A Christmas Carol was published on 19/12/1843, when Bob Cratchit was in his forties, almost seven years after Jacob Marley’s death on Christmas Eve. On Marley’s last Christmas Day, a working day for them all as always, Scrooge said to Cratchit and Marley: “We three will work the same dates next year as this year, except that I’ll cover Cratchit’s birthday so he can have the day off, since Marley never works on his”. On Boxing Day, Scrooge decided to allocate extra work dates for next year to anyone whose number of work dates was going to be below the average of the three of them, bringing them up to exactly that average. Daily, up to and including New Year’s Eve, Scrooge repeated this levelling-up to the new average, never needing fractions of a day.

    What was Bob Cratchit’s full date of birth?

    In the book The Sunday Times Teaser Book 2 (2023), the “levelling-up” process is described as follows:

    … Scrooge decided to allocate extra work dates for the next year to the one whose number of work dates was going to be below the average of the three of them, bringing him up to exactly that average. Daily, up to and including New Year’s Eve, Scrooge repeated this levelling-up for that person to the new average, never needing fractions of a day.

    Which is intended to indicate that only one of the three is “levelled-up” each time the process is applied.

    [teaser3092]

     
    • Jim Randell's avatar

      Jim Randell 5:55 pm on 23 December 2021 Permalink | Reply

      I’m not sure I understand how this is meant to work as a puzzle.

      If Cratchit is in his forties on 1843-12-19, then he was born sometime between 1794 and 1803.

      And, if Marley died on 1836-12-24, his last Christmas Day would be 1835-12-25, so Scrooge was planning the dates for 1836.

      All we know for sure (for the initial schedule) is that they all work every Christmas Day, Marley never works on his birthday, and Scrooge will work on Cratchit’s birthday in 1836 but Cratchit won’t.

      So the number of possible workdays initially scheduled for 1836 is: Scrooge 2-366, Cratchit 1-365, Marley 1-365.

      I found 3429 initial assignments of numbers of work days in 1836 that would allow Scrooge to perform his procedure 6 times.

      For example if the initial number of allocated work days is (99, 268, 308) we have:

      26th: (99, 268, 308), mean = 225 → (225, 268, 308)
      27th: (225, 268, 308), mean = 267 → (267, 268, 308)
      28th: (267, 268, 308), mean = 281 → (281, 281, 308)
      29th: (281, 281, 308), mean = 290 → (290, 290, 308)
      30th: (290, 290, 308), mean = 296 → (296, 296, 308)
      31st: (296, 296, 308), mean = 300 → (300, 300, 308)

      But there doesn’t seem to be any specified conditions to allow us to narrow down these numbers to a set that would allow us to determine a specific date for Cratchit’s birthday.

      However, there is a particular date that suggests itself as the only one of the candidate birthdates that has a certain property, so maybe that is the required answer. And it is the same unique date that we get if we make certain assumptions about the behaviour of Scrooge.

      Solution: [See below]

      Like

      • Jim Randell's avatar

        Jim Randell 10:22 am on 1 January 2022 Permalink | Reply

        The published puzzle text is flawed.

        Apparently the setter intended that only one of the three would be “levelled up” each time the process is applied.

        This leads to a single levelling up process:

        26th: (1, 365, 366), mean = 244 → (244, 365, 366)
        27th: (244, 365, 366), mean = 325 → (325, 365, 366)
        28th: (325, 365, 366), mean = 352 → (352, 365, 366)
        29th: (352, 365, 366), mean = 361 → (361, 365, 366)
        30th: (361, 365, 366), mean = 364 → (364, 365, 366)
        31st: (364, 365, 366), mean = 365 → (365, 365, 366)

        So, before the “levelling up” process started the work days allocated were 1, 365, 366.

        Scrooge must be 366, as he is working an extra day compared to 1835, and there were 365 days in 1835. The extra day worked is the leap day in 1836, and this must also be Cratchit’s birthday.

        Cratchit must be 365, as Marley did not work on his birthday in 1835.

        Hence, Marley must be the 1. He only worked Christmas day.

        So the intended answer was:

        Solution: Bob Cratchit was born on 29th February 1796.

        And this was the answer I suspected, as it was the only date with a certain property in the required range (i.e. the only 29th February), without worrying about the “levelling up” stuff at all.

        Like

  • Unknown's avatar

    Jim Randell 7:30 am on 23 December 2021 Permalink | Reply
    Tags:   

    Brain-Teaser 891: Ups and downs 

    From The Sunday Times, 3rd September 1978 [link]

    An electrician living in a block of flats has played a joke on the tenants by rewiring the lift. The buttons numbered 0 to 9 in the lift should correspond to the ground floor, first floor, etc., but he has rewired them so that although (for his own convenience) the buttons for the ground floor and his own floor work correctly, no other button takes you to its correct floor. Indeed when you get in the lift on the ground floor and go up, three of the buttons take you twice as high as they should, and two buttons take you only half as high as they should.

    The milkman is unaware of the rewiring and so early yesterday morning, rather bleary-eyed, he followed his usual ritual which consists of taking nine pints of milk into the lift, pushing button 9, leaving one pint of milk when the lift stops, pushing button 8, leaving one pint of milk when the lift stops, and so on in decreasing order until, having pushed button and having left his last pint, he usually returns to his van.

    However, yesterday when he tried to follow this procedure all seemed to go well until, having pushed button 1 , when the lift stopped he found a pint of milk already there. So he took the remaining pint back to his van, with the result that just one of the tenants (who lived on one of the floors below the electrician’s) did not get the pint of milk she’d expected.

    The surprising thing was that during the milkman’s ups and downs yesterday he at no time travelled right past the floor which he thought at that time he was heading towards.

    List the floors which received milk, in the order in which the milkman visited them.

    This puzzle is included in the book The Sunday Times Book of Brain-Teasers: Book 1 (1980). The puzzle text above is taken from the book.

    [teaser891]

     
    • Jim Randell's avatar

      Jim Randell 7:32 am on 23 December 2021 Permalink | Reply

      The electrician makes a journey by selecting buttons 9, 8, 7, …, 3, 2, 1, and in the process visits one of the floors twice and one of the floors no times. And the floor that is not visited is a lower number than the electrician’s floor (which is the only button that gives the correct floor).

      I assumed there are exactly 3 buttons that go to floor exactly twice the number on the button, and exactly 2 that go to a floor exactly half the number on the button.

      This Python 3 program chooses the buttons that go to floors twice and half their labelled values, and then fills out the rest of the mapping as it goes along. It runs in 53ms.

      Run: [ @replit ]

      from enigma import (irange, update, product, subsets, diff, singleton, trim, map2str, printf)
      
      # consider a journey made with buttons <bs>, visiting floors <fs> using map <m> (button -> floor)
      def journey(bs, fs, m):
        # are we done?
        if not bs:
          yield (fs, m)
        else:
          (b, f_) = (bs[0], fs[-1])
          # is the button assigned?
          f = m.get(b, None)
          if f is None:
            (ss, upd) = (irange(0, 9), 1)
          else:
            (ss, upd) = ([f], 0)
          # choose a target floor
          for f in ss:
            # if unassigned: cannot be the right floor, or twice or half
            if upd and (f == b or f == 2 * b or b == 2 * f): continue
            # cannot be a previously visited floor, except for the final floor
            if (f in fs) != (len(bs) == 1): continue
            # journey cannot pass the correct floor
            if not (f_ < b < f or f_ > b > f):
              m_ = (update(m, [(b, f)]) if upd else m)
              yield from journey(bs[1:], fs + [f], m_)
      
      # exactly 3 buttons go to twice the number, exactly 2 buttons go to half the number
      for (ds, hs) in product(subsets([1, 2, 3, 4], size=3), subsets([2, 4, 6, 8], size=2)):
        # remaining floors
        rs = diff(irange(1, 9), ds + hs)
        if len(rs) != 4: continue
      
        # choose the floor for the electrician
        for e in rs:
          if e == 1: continue
      
          # initial map
          m0 = { 0: 0, e: e }
          m0.update((k, 2 * k) for k in ds) # doubles
          m0.update((k, k // 2) for k in hs) # halfs
      
          # consider possible journeys for the milkman
          for (fs, m) in journey([9, 8, 7, 6, 5, 4, 3, 2, 1], [0], m0):
      
            # the unvisited floor is lower than e
            u = singleton(x for x in irange(1, 9) if x not in fs)
            if u is None or not (u < e): continue
      
            # output solution
            printf("{fs} {m}", fs=trim(fs, head=1, tail=1), m=map2str(m, arr='->'))
      

      Solution: The milkman visited floors: 7, 4, 2, 3, 5, 8, 6, 9.

      He then returns to floor 2, and finds he has already visited.

      The rewired map of button → floor is:

      0 → 0
      1 → 2 (twice)
      2 → 9
      3 → 6 (twice)
      4 → 8 (twice)
      5 → 5 (electrician’s floor)
      6 → 3 (half)
      7 → 2
      8 → 4 (half)
      9 → 7

      Like

  • Unknown's avatar

    Jim Randell 9:59 am on 21 December 2021 Permalink | Reply
    Tags:   

    Teaser 2849: Swift tailor 

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

    When measuring gentlemen’s chest sizes in inches, the tailors five foot long tape overlapped so that the set of numbers 1 to 9 was aligned with a consecutive set of higher numbers.

    Taking each pair of these nine aligned lower and higher numbers as a fraction the tailor saw that just two of the nine “fractions” were in their simplest form and did not cancel down (i.e. the pair of numbers had no common factor greater than one).

    All of this was also true when he measured the smaller waist size.

    What (in inches) were the gentleman’s chest and waist sizes?

    [teaser2849]

     
    • Jim Randell's avatar

      Jim Randell 10:00 am on 21 December 2021 Permalink | Reply

      Assuming the tape measure is graduated 1″ … 60″.

      The smallest possible measurement is: 1/10 … 9/18 corresponding to a measurement of 9″ (although that is ludicrously small). And the largest is: 1/52 … 9/60 (corresponding to 51″).

      This Python program runs in 46ms.

      Run: [ @replit ]

      from enigma import (irange, is_coprime, printf)
      
      # consider possible measurements
      for m in irange(9, 51):
        # count how many pairs are co-prime
        pairs = ((i, m + i) for i in irange(1, 9))
        ps = list(p for p in pairs if is_coprime(*p))
        # we are looking for measurements with 2 co-prime pairs
        if len(ps) == 2:
          printf("m={m} {ps}")
      

      Solution: The measurements are: chest = 42″; waist = 30″.

      When the measurement is 30″ we get the following lowest term fractions: 1/31, 7/37.

      When the measurement is 42″ we get the following lowest term fractions: 1/43, 5/47.

      Like

    • Hugh+Casement's avatar

      Hugh+Casement 1:12 pm on 21 December 2021 Permalink | Reply

      That works out at 76 and 107 cm: a fine figure of a man!
      Somehow I find 84 and 90 cm more realistic.

      Like

  • Unknown's avatar

    Jim Randell 10:13 am on 19 December 2021 Permalink | Reply
    Tags: by: Mr. A. C. Jolliffe   

    A Brain Teaser: Rose beds 

    From The Sunday Times, 25th December 1955 [link]

    In my garden I had, until recently, two square rose beds of different sizes. At my wife’s suggestion I modified the layout, making two square plots of equal size but leaving the area devoted to roses unchanged.

    My two next-door neighbours, as it happened, were also the possessors of square rose beds — each had three, one of a certain size with two equal beds of another size, the dimensions being different for the two neighbours. They, admiring the change in my garden, decided to follow suit. Each now has three square beds of equal size, but each has kept the same area as before devoted to roses. We have discovered that all our eight rose beds are now the same size, also that the side of every rose bed was and is an integral number of feet.

    Given that the final beds are of the smallest possible size fulfilling the conditions, how large were our original beds?

    This is one of the occasional Holiday Brain Teasers published in The Sunday Times prior to the start of numbered Teasers in 1961. Three 1 guinea book tokens were offered for the first 3 correct solutions.

    [teaser-1955-12-25] [teaser-unnumbered]

     
    • Jim Randell's avatar

      Jim Randell 10:13 am on 19 December 2021 Permalink | Reply

      I’m assuming “leaving the area devoted to roses unchanged”, means the total area of the plots after the change is the same as it was before.

      So equating the setters before and after areas we get:

      a² + b² = 2x²

      And using the same value of x for the neighbours we have:

      a² + 2b² = 3x²

      This program finds the smallest possible shared value of x, and the corresponding (a, b) values. It runs in 49ms.

      Run: [ @replit ]

      from enigma import (irange, inf, sq, is_square, printf)
      
      # find solutions for a^2 + k.b^2 = n
      def solve(k, n):
        for b in irange(1, inf):
          a2 = n - k * sq(b)
          if not (a2 > 0): break
          a = is_square(a2)
          if a is None: continue
          yield (a, b)
      
      # consider the final size
      for x in irange(1, inf):
      
        # find: a^2 + b^2 = 2x^2
        ss1 = list((a, b) for (a, b) in solve(1, 2 * sq(x)) if a < b)
        if not ss1: continue
      
        # find: a^2 + 2b^2 = 3x^2
        ss2 = list((a, b) for (a, b) in solve(2, 3 * sq(x)) if a != b)
        if not (len(ss2) > 1): continue
      
        # output solution
        printf("x={x}; ss1={ss1} ss2={ss2}")
        break
      

      Solution: The original beds were: setter = 7×7 + 23×23; neighbours = 25×25 + 2(11×11), 23×23 + 2(13×13).

      The size of the final beds is: 17×17 (the setter has 2, and each of the neighbours has 3).

      Like

  • Unknown's avatar

    Jim Randell 4:34 pm on 17 December 2021 Permalink | Reply
    Tags:   

    Teaser 3091: Birthday money 

    From The Sunday Times, 19th December 2021 [link] [link]

    My two daughters were born on the same day but seven years apart. Every birthday, with only one year’s exception, I have given them both five pounds for each year of their age. They are now grown-up, but I have continued to do this on their birthdays, except for the one year when I couldn’t afford to give either of them anything. Averaged out over all of their birthdays, including the one for which they received nothing, my elder daughter has now received 21 per cent more per birthday than her younger sister.

    How much in total have I given to my daughters as birthday presents?

    [teaser3091]

     
    • Jim Randell's avatar

      Jim Randell 5:08 pm on 17 December 2021 Permalink | Reply

      This Python program finds the solution constructively. It runs in 52ms.

      Run: [ @replit ]

      from enigma import (Rational, irange, unzip, printf)
      
      Q = Rational()
      
      # look for solutions
      def solve():
        # initial ages
        ages = [7, 0]
      
        # collect gifts (newest first)
        gifts = list(list(5 * x for x in irange(age, 1, step=-1)) for age in ages)
        totals = list(sum(x) for x in gifts)
      
        while True:
          # add in data for the next year
          for (i, _) in enumerate(ages):
            ages[i] += 1
            v = 5 * ages[i]
            gifts[i].insert(0, v)
            totals[i] += v
      
          # consider missing years
          for ms in unzip(gifts):
            # calculate averages without missing year
            avgs = list(Q(t - m, a) for (t, m, a) in zip(totals, ms, ages))
      
            # look for avgs[0] = 121% of avgs[1]
            if 100 * avgs[0] == 121 * avgs[1]:
              yield (ages, totals, ms)
      
      # find the first solution
      for (ages, totals, ms) in solve():
        t = sum(totals) - sum(ms)
        printf("total = {t}; ages = {ages}; missing={ms}")
        break
      

      Solution: The total of the gifts is £ 6660.

      The daughters are currently aged 40 and 33, and the missing amounts are £ 140 and £ 105, when the daughters were 28 and 21.

      In total the elder daughter has received £ 3960 (an average of £ 99 per year), and the younger has received £ 2700 (an average of £ 81 + 9/11 per year).

      And we have:

      121% of (81 + 9/11)
      = (121/100) × (900/11)
      = 99


      Analytically we see that the £ 5 multiplier cancels out and we are looking for values of:

      (T(n + 7) − (k + 7)) / (n + 7) = (121/100) (T(n) − k) / n

      where: n is the age of the younger daughter, and k ∈ [1, n] is her age in the missing year.

      This simplifies to:

      k = (3n² − 76n − 479)n / (6n + 242)

      And we can then just look for the first n that gives a viable value for k:

      from enigma import (irange, inf, div, T, printf)
      
      # consider age of youngest daughter
      for n in irange(1, inf):
        # calculate missing year
        k = div(((3 * n - 76) * n - 479) * n, 6 * n + 242)
        if not (k is None or k < 0 or k > n):
          # output solution
          t1 = T(n) - k
          t2 = T(n + 7) - (k + 7)
          t = 5 * (t1 + t2)
          printf("[n={n} k={k}] total = {t}; ages = ({n+7}, {n})")
          break
      

      Further analysis shows that in order for k to be positive we require: n > (38 + √2881) / 3 ≈ 30.56.

      And for k ≤ n we require: n ≤ 103/3 ≈ 34.33.

      So we only need to check k ∈ [31, 34], which we can do manually.

      n = 31 ⇒ k = 3.48…
      n = 32 ⇒ k = 11.87…
      n = 33 ⇒ k = 21
      n = 34 ⇒ k = 30.87…

      Like

    • GeoffR's avatar

      GeoffR 9:12 am on 18 December 2021 Permalink | Reply

      % A Solution in MiniZinc
      include "globals.mzn";
      
      % Assume max daughters ages are 63 and 70 years and father is in his nineties.
      % Max UB amount - 1st daughter = 63 * 64 div 2 * 5 = 10080, say 10100
      % Max UB amount - 2nd daughter = 70 * 71 div 2 * 5 = 12425, say 12500
      
      var 1..63:D1; % max 1st daughter's age
      var 1..70:D2; % max 2nd daughter's age
      var 1..63: MA; % missed age year
      
      % Total gift amounts for two daughters
      var 5..10100: D1_tot;
      var 5..12500: D2_tot;
      var 10..22600: Total;
      
      % Elder daughter is 7 years older than her sister
      constraint D2 == D1 + 7;
      
      % Total gift amounts, allowing for the missing age year
      constraint D1_tot == 5 * D1 * (D1 + 1) div 2 - 5 * MA;
      constraint D2_tot == 5 * D2 * (D2 + 1) div 2 - 5 * (MA + 7);
      constraint Total == D1_tot + D2_tot;
      
      % Elder daughter received 21 per cent more per birthday than her sister
      % (D2_tot/D2) / (D1_tot/D1) = 121/100
      constraint 100 * D2_tot * D1 == 121 * D1_tot * D2;
      
      solve satisfy;
      
      output ["Total (£) = " ++ show(Total) ++ "\n" ++ "Daughter's ages are " ++ 
      show(D1) ++ " and " ++ show(D2) ++ " years"]; 
      
      
      
      

      Like

    • NigelR's avatar

      NigelR 3:23 pm on 19 December 2021 Permalink | Reply

      apologies Jim – I haven’t worked out how to post code properly. Is there a guide somewhere, please?

      acum,bcum=140,0  #140 is accumulated gifts for daughter 1 for birthdays 1-7
      for y in range(8,90): #start from 1st birthday for daughter 2
          acum+=5*y
          bcum+=5*(y-7)
          for i in range (8,y):  #iterate over previous years to remove 1 year at a time
              if abs(((acum-5*i)/y)-1.21*((bcum-(5*(i-7)))/(y-7)))<0.0001:
                  print("total gifted is:",(acum-5*i)+(bcum-5*(i-7)))
      

      Like

      • Jim Randell's avatar

        Jim Randell 3:44 pm on 19 December 2021 Permalink | Reply

        Hi,

        You can include code like this:

        [code language="python"]
        your code here
        [/code]
        

        For longer programs (80 lines for more) you can also include the collapse="true" parameter, to hide it until clicked on.

        Be careful though,it is not possible to edit a comment in WordPress once it is posted.

        Like

    • Tony Brooke-Taylor's avatar

      Tony Brooke-Taylor 7:31 am on 20 December 2021 Permalink | Reply

      With a bit of rearrangement of a formula for the ratio of averages you can pretty much solve this manually. Once you have the limits you can almost intuit the correct value for the younger daughter’s age but the program below loops until it finds a solution.

      # Find real roots of a quadratic equation with conventional coefficients a, b, c
      def quad_roots(a, b, c):
          r = (b ** 2 - 4 * a * c)
          if r >= 0:
              low = (-b - r**(1/2))/2/a
              up = (-b + r**(1/2))/2/a
              return low, up
      
      
      # Define missing_year as the age of the younger daughter when the gift was missed
      # Make this the subject of the equation formed from taking the ratio of averages given
      
      # The lower bound for the younger age can be inferred from the condition that missing_year exceeds 0
      low_lim = max([int(r) for r in quad_roots(3, -76, -479) if r > 0]) + 1
      # The upper bound for the younger age can be inferred from the condition that it exceeds missing_year
      up_lim = max([int(r) for r in quad_roots(3, -(76 + 6), -(479 + 242)) if r > 0]) + 1
      
      # Find the value for the age now of the younger daughter, such that missing_year is an integer
      for young_age, missing_year in ((n, (3 * n ** 2 - 76 * n - 479) / (6 * n + 242) * n) for n in range(low_lim, up_lim)):
          if missing_year % 1 == 0:
              total = 0
              for d in [0, 7]:
                  total += ((young_age + d) * ((young_age + d)+1)/2 - (missing_year + d))
              print("Total given to both daughters is", total * 5)
              break
      
      

      Like

  • Unknown's avatar

    Jim Randell 11:18 am on 16 December 2021 Permalink | Reply
    Tags: ,   

    Teaser 2844: Children’s children 

    From The Sunday Times, 26th March 2017 [link] [link]

    The head teacher’s retirement celebration was attended by many former pupils. These included Adam, Brian, Colin and David, whose sons and grandsons had also attended the school – actually different numbers of grandsons for each of them, with Adam having the most. Their sons were Eric, Fred, George, Harry and Ivan, and the sons of the sons were John, Keith, Lawrence, Michael, Norman and Oliver.

    Altogether Adam and Brian had sons Eric, Fred and one other; altogether Adam and Colin had sons George and one other; altogether Eric, George and Harry had sons Keith, Michael, Norman and one other; and altogether Harry and Ivan had sons Lawrence, Norman and one other.

    The retirement gift was presented by the fathers of John’s and Oliver’s fathers.

    Who were they?

    As stated there are multiple solutions to this puzzle.

    This puzzle was not included in the published collection of puzzles The Sunday Times Brainteasers Book 1 (2019).

    There are now 600 puzzles available on S2T2.

    [teaser2844]

     
    • Jim Randell's avatar

      Jim Randell 11:19 am on 16 December 2021 Permalink | Reply

      As stated the puzzle has multiple solutions.

      The following Python program builds the 8 possible family trees that fit the described situation.

      It runs in 85ms.

      Run: [ @replit ]

      from enigma import (subsets, peek, product, map2str, join, printf)
      
      # map ks to vs
      def make_map(ks, vs):
        for ss in subsets(ks, size=len(vs), select='M'):
          d = dict((k, list()) for k in ks)
          for (k, v) in zip(ss, vs):
            d[k].append(v)
          yield d
      
      # find viable father -> sons mappings
      def check_fs(fs):
      
        # "A, B have sons E, F and one other"
        s = fs['A'] + fs['B']
        if not (len(s) == 3 and 'E' in s and 'F' in s): return False
      
        # "A, C have sons G and one other"
        s = fs['A'] + fs['C']
        if not (len(s) == 2 and 'G' in s): return False
      
        # looks OK
        return True
      
      # collect viable maps
      ffs = list(fs for fs in make_map('ABCD', 'EFGHI') if check_fs(fs))
      
      # find viable son -> grandsons maps
      def check_sg(sg):
          
        # "E, G, H have sons K, M, N and one other"
        s = sg['E'] + sg['G'] + sg['H']
        if not (len(s) == 4 and 'K' in s and 'M' in s and 'N' in s): return False
      
        # "H, I have sons L, N and one other"
        s = sg['H'] + sg['I']
        if not (len(s) == 3 and 'L' in s and 'N' in s): return False
      
        # looks OK
        return True
      
      # collect viable maps
      sgs = list(sg for sg in make_map('EFGHI', 'JKLMNO') if check_sg(sg))
      
      # find the father of x in map d
      def father(x, d):
        return peek(k for (k, v) in d.items() if x in v)
      
      # choose the maps
      for (fs, sg) in product(ffs, sgs):
      
        # A, B, C, D have different numbers of grandsons
        s = list(sum(len(sg[s]) for s in fs[f]) for f in 'ABCD')
        if len(set(s)) != 4: continue
        # A has the most
        if s[0] != max(s): continue
      
        # grandfather of J and O
        gJ = father(father('J', sg), fs)
        gO = father(father('O', sg), fs)
        # they must be different people
        if gJ == gO: continue
      
        # output solution
        f = lambda s: join(s, sep="+")
        fmt = lambda m: map2str((k, f(v)) for (k, v) in m.items())
        printf("{gs} [grandfather(J) = {gJ}; grandfather(O) = {gO}]", gs=f(sorted([gJ, gO])))
        printf("  father -> sons: {fs}", fs=fmt(fs))
        printf("  son -> grandsons: {sg}", sg=fmt(sg))
        printf()
      

      Solution: One of the presenters is Adam, but the other can be any of: Brian, Colin, or David.

      The originally published solution is: “Adam and David”, but a later correction was made (with Teaser 2846) noting there are three valid solutions to the puzzle (given above).


      However, there is a unique solution if the end of the puzzle is changed to:

      The retirement gift was presented by the paternal grandfather of John and Oliver.

      Who was he?

      We can change the sense of the test at line 68 to ensure that the grandfathers of John and Oliver are the same person, and we find there are 2 possible family trees that lead to this situation, but in both cases the grandfather is Brian.

      Like

    • Hugh+Casement's avatar

      Hugh+Casement 8:34 am on 17 December 2021 Permalink | Reply

      Without trying Jim’s program, I think it’s like this:
      A’s son is H whose sons are L, N, and either K or M. D’s son is I who has no son.
      C’s son is G whose son is M or K (whichever is not H’s son).
      Brian has sons E (who has no sons) and F who is the father of J and O.

      Like

  • Unknown's avatar

    Jim Randell 4:35 pm on 14 December 2021 Permalink | Reply
    Tags:   

    Brain-Teaser 890: Round pond boat race 

    From The Sunday Times, 27th August 1978 [link]

    In our park is a circular pond exactly 50 metres in diameter, which affords delight to small boys who go down with ships.

    Two such youngsters, Arthur and Boris, took their model motor-cruisers there the other morning, and decided on a race. Each was to start his boat from the extreme North of the pond at the same moment, after which each was to run round the pond to await his boat’s arrival. The moment it touched shore its owner was to grab it by the bows and run with it directly to the South gate of the park, situated exactly 27 metres due South of the Southern edge of the pond. Both boats travelled at the same speed (1 metre in 3 seconds) but both owners, burdened with their respective craft, could manage only 3 metres in 4 seconds over the rough grass.

    When the race started, Arthur’s boat headed due South, but that of Boris headed somewhat East of South and eventually touched shore after travelling 40 metres in a straight line.

    Who arrived first at the gate, and by what time margin (to the nearest second)?

    This puzzle is included in the book The Sunday Times Book of Brain-Teasers: Book 1 (1980). The puzzle text above is taken from the book.

    [teaser890]

     
    • Jim Randell's avatar

      Jim Randell 4:36 pm on 14 December 2021 Permalink | Reply

      The boats start at S and travel to A and B, and are then carried to the gate at G. O is the centre of the pond, GX is tangent to the pond.

      For A, the distance travelled by the boat is SA = 50m, and the distance on foot is AG = 27m.

      So the total time taken is: 50 × 3 + 27 × 4/3 = 186 seconds.

      For B, we see that the triangle ABS is inscribed in a semicircle, so has a right angle at B, and the sides SA = 50m, SB = 40m (so AB = 30m), so if θ is the angle ASB we have:

      cos(θ) = 40/50 = 4/5

      We can then calculate the straight line distance BG using the cosine rule on triangle GSB:

      (BG)² = (GS)² + (BS)² − 2(GS)(BS)cos(θ)
      (BG)² = 77² + 40² − 2×77×40×4/5
      (BG)² = 2601
      BG = 51

      For B, the distance travelled by the boat is SB = 40m, and the straight line distance on foot is BG = 51m.

      So the total time taken is: 40 × 3 + 51 × 4/3 = 188 seconds.

      So it looks like A beats B by 2 seconds.

      However looking at the diagram, we note that the line BG actually passes through the pond, and so B would have to run around the circumference of the pool (along the arc BX), until he can make a straight line to G (along XG, a tangent to the circle).

      The straight line distance along the tangent, XG, is:

      (XG)² + 25² = (25 + 27)²
      (XG)² = 2079
      XG = 3√(231)

      We can calculate the angle SOB using the cosine rule:

      (SB)² = (OS)² + (OB)² − 2(OS)(OB)cos(𝛂)
      cos(𝛂) = (2×25² − 40²) / 2×25²
      cos(𝛂) = −7/25

      The amount of arc travelled, φ (the angle BOX), is then given by:

      φ = ψ − (𝛂 − 𝛑/2)

      Where ψ is the angle OGX, which we can calculate using the right angled triangle OXG:

      cos(ψ) = XG / (OB + BG)
      cos(ψ) = 3√(231)/52

      As expected, the difference made by following the arc instead of the straight line is not enough to change the result (which is given to the nearest second).

      from math import acos
      from enigma import (fdiv, sq, sqrt, pi, printf)
      
      # boat time
      boat = lambda d: d * 3
      
      # foot time
      foot = lambda d: fdiv(d, 0.75)
      
      # given distances
      R = 25
      SA = 2 * R
      SB = 40
      AG = 27
      
      # exact calculation?
      exact = 1
      
      # calculate time for A
      A = boat(SA) + foot(AG)
      printf("A = {A:.6f} sec")
      
      # calculate time for B
      SG = SA + AG
      cos_theta = fdiv(SB, SA)
      BG = sqrt(sq(SG) + sq(SB) - 2 * SG * SB * cos_theta)
      
      B = boat(40) + foot(BG)
      printf("B = {B:.6f} sec (approx)")
      
      if exact:
        # calculate XG
        XG = sqrt(sq(R + AG) - sq(R))
      
        # alpha is the angle SOB
        cos_alpha = fdiv(2 * sq(R) - sq(SB), 2 * sq(R))
        
        # psi is the angle OGX
        cos_psi = fdiv(XG, R + AG)
      
        # calculate phi (amount of arc)
        psi = acos(cos_psi)
        alpha = acos(cos_alpha)
        phi = psi - (alpha - 0.5 * pi)
      
        # calculate the exact distance for B
        BX = R * phi
        B = boat(40) + foot(BX + XG)
        printf("B = {B:.6f} sec (exact) [extra distance = {xB:.6f} m]", xB=BX + XG - BG)
        
      # calculate the difference
      d = abs(A - B)
      printf("diff = {d:.6f} sec")
      

      Solution: Arthur beats Boris by approximately 2 seconds.

      Following the arc is 3.95cm longer than the straight line distance, and adds 53ms to B’s time.

      The actual shortest distance from B to G can be expressed as:

      3\sqrt{231}\; +\; 25\cos ^{-1}\left( \frac{7}{52}\; +\; \frac{18\sqrt{231}}{325} \right)

      which is approximately 51.039494 m, compared to the straight line distance BG of 51 m.

      Like

      • galoisest's avatar

        galoisest 4:28 pm on 15 December 2021 Permalink | Reply

        Nice analysis Jim, I completely missed that the straight line goes through the pond.

        The simplest expression I can get for the difference including the arc is:

        100/3*(pi-acos(25/52)-2*acos(3/5)) + 4sqrt(231) – 66

        Like

        • Jim Randell's avatar

          Jim Randell 4:37 pm on 15 December 2021 Permalink | Reply

          It was more obvious in my original diagram (which had the line BG, instead of XG).

          But in this case it doesn’t matter if you spot this or not – the answer is unaffected. (I wonder if the setter intended us to calculate the exact distance, or just work out the length of BG).

          Like

  • Unknown's avatar

    Jim Randell 10:33 am on 12 December 2021 Permalink | Reply
    Tags: by: Mr. W. Blackman   

    Brain Teaser: Tea table talk 

    From The Sunday Times, 26th December 1954 [link]

    The Sales Manager of the Kupper Tea Company came into the Chief Accountant’s office. “I’ve got to report to the Chairman on the results of our new policy of selling pound packets only in four qualities only”, he said, “Which is the most popular brand — the 3s. 11d., 4s. 11d., 5s. 11d., or 6s. 11d.?”.

    “When reduced to pounds, shillings and pence”, replied the man of figures, the sales of each brand for last month differ from each other only in the pence column, and there only to the extent that the figures are 1d., 2d., 3d., and 4d., though not respectively”.

    “Very Interesting,” said the Sales Manager, but the Chairman will want a plain “yes” or “no” to whether we have reached our sales target. What is the answer to that?”.

    “The answer to that, my boy”, replied the Chief Accountant, “is all the further information you need to calculate the complete figures for yourself”.

    What are the figures?

    [Note: £1 = 20s, and 1s = 12d]

    This is one of the occasional Holiday Brain Teasers published in The Sunday Times prior to the start of numbered Teasers in 1961. Prizes of £3, £2 and £1 were offered for the first 3 correct solutions.

    [teaser-1954-12-26] [teaser-unnumbered]

     
    • Jim Randell's avatar

      Jim Randell 10:35 am on 12 December 2021 Permalink | Reply

      The following program steps through multiples of the largest price, and looks for multiples of the other prices which come in close to the same price, but with differing “pence” values.

      We find that there are many sets of 4 sales figures that differ only in the pence column, with values of (1, 2, 3, 4).

      If the sales target had been met (or exceeded) we would not know which of these to choose (if we find one set of figures that works, any larger set of figures would also work).

      However, if the sales target had not been met, and that is enough information to work out what the figures are, then we must be interested in the lowest set of possible sales figures, and the target must be higher than this, but less than the second lowest possible set of figures.

      The program runs in 166ms, so is fast enough, but this isn’t a suitable approach for a manual solution.

      Run: [ @replit ]

      from enigma import irange, inf, div, singleton, unpack, printf
      
      # pence -> (pounds, shillings, pence)
      def d2psd(n):
        (n, d) = divmod(n, 12)
        (p, s) = divmod(n, 20)
        return (p, s, d)
      
      # (pounds, shillings, pence) -> pence
      def psd2d(p, s, d):
        return 240 * p + 12 * s + d
      
      # solve for the specified prices, (A, B, C, D)
      def solve(A, B, C, D):
        # look for multiples of the largest price
        for n in irange(0, inf, step=D):
          (p, s, d) = d2psd(n)
          if 0 < d < 5:
            # so the other amounts were are interested in are...
            r = dict()
            for d_ in (1, 2, 3, 4):
              if d_ == d: continue
              k = singleton(x for x in (A, B, C) if div(psd2d(p, s, d_), x))
              if k:
                r[k] = (p, s, d_)
              else:
                break
            # have we found a value for each d?
            if len(r.keys()) == 3:
              r[D] = (p, s, d)
              yield r
      
      # prices (in ascending order)
      prices = list(psd2d(0, s, 11) for s in (3, 4, 5, 6))
      
      # look for the smallest solution
      for r in solve(*prices):
        for (k, (p, s, d)) in sorted(r.items(), key=unpack(lambda k, v: v)):
          n = div(psd2d(p, s, d), k)
          (_, ks, kd) = d2psd(k)    
          printf("({p}, {s}s, {d}d) = {n} pkts @ ({ks}s, {kd}d) each")
        printf()
        break
      

      Solution: The sales figures are:

      £53878, 1s, 1d = 182123 pkts @ 5s, 11d each
      £53878, 1s, 2d = 275122 pkts @ 3s, 11d each
      £53878, 1s, 3d = 219165 pkts @ 4s, 11d each
      £53878, 1s, 4d = 155792 pkts @ 6s, 11d each

      And the target must be above this.

      The next set of figures starts at £77098, 0s, 1d, so the target must be below this (otherwise there would be a choice of two sets of figures).

      Like

    • Hugh+Casement's avatar

      Hugh+Casement 2:10 pm on 12 December 2021 Permalink | Reply

      I wouldn’t like to have had to work that out in 1954, with no computer to hand.
      It would have been easier if the sales had been all the same: £68088 14s. 1d. is the LCM of the four packet prices, each a prime number of pence.

      In the days before the ubiquitous teabags, tea was normally sold in quarter-pound packets.
      I seem to remember a price of about 1s. 6d., but probably less in the ’50s.

      Like

    • GeoffR's avatar

      GeoffR 9:00 am on 14 December 2021 Permalink | Reply

      % A Solution in MiniZinc
      include "globals.mzn";
      
      % Four standard sale prices (3s, 11d, 4s, 11d, 5s, 11d, 6s, 11d)
      int: P1 == 47; int: P2 == 59; int: P3 == 71; int: P4 == 83;
      
      % Amounts sold for each packet price
      var 100000..300000:pkt1; var 100000..300000:pkt2;
      var 100000..300000:pkt3; var 100000..300000:pkt4;
      
      constraint all_different([pkt1,pkt2,pkt3,pkt4]);
      
      % testing range for sales totals is £50,000 to £60,000
      % range values in old pence (240d = £1)
      var 12000000..14400000: T1;  
      var 12000000..14400000: T2;
      var 12000000..14400000: T3;
      var 12000000..14400000: T4;
      
      constraint T1 == pkt1 * P1 /\ T2 == pkt2 * P2
      /\ T3 == pkt3 * P3 /\ T4 == pkt4 * P4;
      
      constraint all_different([T1, T2, T3, T4]);
      
      % the four total sales values are 1d, 2d, 3d and 4d different 
      constraint max([T1, T2, T3, T4]) - min([T1, T2, T3, T4]) == 3;
      
      solve satisfy;
      
      output ["Totals(old pence) [T1, T2, T3, T4] = " ++ show([T1, T2, T3, T4]) 
      ++ "\nPackets (No.) = " ++ show([pkt1, pkt2, pkt3, pkt4])];
      
      % Totals(old pence) [T1, T2, T3, T4] = [12126799, 12126801, 12126800, 12126798]
      % Packets (No.) = [258017, 205539, 170800, 146106]
      % ----------
      % Totals(old pence) [T1, T2, T3, T4] = [12193116, 12193117, 12193114, 12193115]
      % Packets (No.) = [259428, 206663, 171734, 146905]
      % ----------
      % Totals(old pence) [T1, T2, T3, T4] = [12930734, 12930735, 12930733, 12930736]
      % Packets (No.) = [275122, 219165, 182123, 155792]  *** Published answer ***
      % ----------
      % Totals(old pence) [T1, T2, T3, T4] = [13664874, 13664872, 13664873, 13664871]
      % Packets (No.) = [290742, 231608, 192463, 164637]
      % ----------
      % ==========
      
      
      

      I worked in old decimal pence (240p = £1), looking for 1d differences in total sales values between 12,000,000 and 14,400,000 sales totals, in old pence. This search range is £50,000 to £60,000 in current money terms and was used to reduce search time. The Chuffed solver was used.

      Using Python’ divmod function for converting old money totals to current monetary values:

      T1 = 12930734 in old pence is:
      divmod(12930734,240) = (53878, 14) = £53878 1s 2d

      T2 = divmod(12930735,240)
      = (53878, 15) = £53878 1s 3d

      T3 = divmod(12930733,240)
      = (53878, 13) = £53878 1s 1d

      T4 = divmod(12930736,240)
      = (53878, 16) = £53878 1s 4d

      There were several solutions, including the published solution.

      Like

  • Unknown's avatar

    Jim Randell 1:17 pm on 10 December 2021 Permalink | Reply
    Tags:   

    Teaser 3090: Main line 

    From The Sunday Times, 12th December 2021 [link] [link]

    Anton and Boris live next to a railway line. One morning a goods train passed Anton’s house travelling south just as a slower train passed Boris’s house travelling north. The goods train passed Boris’s house at the same time as a passenger train, heading north at a speed that was half as fast again as the goods train. Similarly, as the slower train passed Anton’s house it passed a passenger train; this was heading south at a speed that was three times as great as that of the slower train.

    The passenger trains then passed each other at a point 25 kilometres from Anton’s house before simultaneously passing the two houses.

    All four trains travelled along the same route and kept to their own constant speeds.

    How far apart do Anton and Boris live?

    [teaser3090]

     
    • Jim Randell's avatar

      Jim Randell 1:38 pm on 10 December 2021 Permalink | Reply

      This is an exercise is generating and solving simultaneous equations. No programming necessary.

      If we suppose B lives a distance d from A.

      Initially (at time 0) if the goods train passes A travelling south at speed 2v, then it reaches B at a time of (d / 2v).

      At this time, the passenger train, with a speed of 3v passes B, heading north.

      And the slow train, travelling at speed 2fv (i.e. some fraction of v), reaches A at a time of (d / 2fv).

      And at this time a train travelling at 6fv passes A heading south.

      These trains pass at time t1 at a point 25 km south of A:

      t1 = (d / 2fv) + (25 / 6fv) = (3d + 25) / 6fv
      t1 = (d / 2v) + ((d − 25) / 3v) = (5d − 50) / 6v
      ⇒ f = (3d + 25) / (5d − 50)

      And then at time (t1 + t2) the two trains pass A and B:

      t2 = 25 / 3v
      t2 = (d − 25) / 6fv
      ⇒ f = (d − 25) / 50

      Equating these:

      (3d + 25) / (5d − 50) = (d − 25) / 50
      10(3d + 25) = (d − 25)(d − 10)
      30d + 250 = d² − 35d + 250
      d² − 65d = 0
      ⇒ d = 65

      So A and B are 65 km apart, and f = 4/5.

      We are not given any times, so we cannot determine the actual speeds of the trains.

      Solution: Anton and Boris live 65 km apart.

      Like

  • Unknown's avatar

    Jim Randell 11:27 am on 9 December 2021 Permalink | Reply
    Tags:   

    Teaser 2843: Child’s play 

    From The Sunday Times, 19th March 2017 [link] [link]

    Liam has a set of cards numbered from one to twelve. He can lay some or all of these in a row to form various numbers. For example the four cards:

    6, 8, 11, 2

    give the five-figure number 68112. Also, that particular number is exactly divisible by the number on each of the cards used.

    In this way Liam used his set of cards to find another much larger number that was divisible by each of the numbers on the cards used — in fact he found the largest such possible number.

    What was that number?

    [teaser2843]

     
    • Jim Randell's avatar

      Jim Randell 11:29 am on 9 December 2021 Permalink | Reply

      To reduce the search space we can use some shortcuts.

      Considering the cards that are included in the number, if the “10” card is included, then it would have to appear at the end, and would preclude the use of cards “4”, “8”, “12”.

      Similarly if “5” is included, and any even card, then the number must end in “10” and the cards “4”, “8”, “12” are excluded.

      If any of the cards “3”, “6”, “9”, “12” are included then the overall digit sum must be a multiple of 3.

      Similarly if “9” is included, then the overall digit sum must be a multiple of 9.

      If any of the even cards (“2”, “4”, “6”, “8”, “10”) are used, the resulting number must also be even.

      This Python program uses a number of shortcuts. It considers the total number of digits in the number, as once a number is found we don’t need to consider any number with fewer digits. It runs in 263ms.

      Run: [ @replit ]

      from enigma import (enigma, irange, group, subsets, Accumulator, join, printf)
      
      # the cards
      cards = list(irange(1, 12))
      
      # map cards to their digit sum, and number of digits
      dsum = dict((x, enigma.dsum(x)) for x in cards)
      ndigits = dict((x, enigma.ndigits(x)) for x in cards)
      
      # find maximum arrangement of cards in ss
      def find_max(ss):
        # look for impossible combinations
        if (10 in ss) and (4 in ss or 8 in ss or 12 in ss): return
        even = any(x % 2 == 0 for x in ss)
        if (5 in ss and even) and (4 in ss or 8 in ss or 12 in ss): return
        # calculate the sum of the digits
        ds = sum(dsum[x] for x in ss)
        # check for divisibility by 9
        if (9 in ss) and ds % 9 != 0: return
        # check for divisibility by 3
        if (3 in ss or 6 in ss or 12 in ss) and ds % 3 != 0: return
        # look for max rearrangement
        r = Accumulator(fn=max)
        fn = (lambda x: (lambda x: (-len(x), x))(str(x)))
        for s in subsets(sorted(ss, key=fn, reverse=1), size=len, select="P"):
          if even and s[-1] % 2 != 0: continue
          # done, if leading digits are less than current max
          if r.value and s[0] != r.data[0] and str(s[0]) < str(r.value): break
          # form the number
          n = int(join(s))
          if all(n % x == 0 for x in ss): r.accumulate_data(n, s)
        return (r.value, r.data)
      
      # sort subsets of cards into the total number of digits
      d = group(subsets(cards, min_size=1), by=(lambda ss: sum(ndigits[x] for x in ss)))
      
      r = Accumulator(fn=max)
      for k in sorted(d.keys(), reverse=1):
        printf("[considering {k} digits ...]")
      
        for ss in d[k]:
          rs = find_max(ss)
          if rs is None: continue
          r.accumulate_data(*rs)
      
        if r.value: break
      
      printf("max = {r.value} [{s}]", s=join(r.data, sep=","))
      

      Solution: The number is 987362411112.

      The cards are: (1, 2, 3, 4, 6, 7, 8, 9, 11, 12).

      Like

      • Frits's avatar

        Frits 6:52 pm on 9 December 2021 Permalink | Reply

        If “5” is included then the number must end in “10” or “5” and the cards “4”, “8”, “12” are excluded (not relying on an even card). I got this from Brian’s solution on his puzzle site.

        Like

        • Jim Randell's avatar

          Jim Randell 10:04 am on 10 December 2021 Permalink | Reply

          @Frits: Good point.

          So if “5” or “10” are used, none of “4”, “8”, “12” can be used. And vice versa, if “4”, “8” or “12” are used, none of “5” or “10” can be used. So at least 3 digits must be absent, and we can start the search from 12 digits.

          Here’s a neater version of my code:

          from enigma import (enigma, irange, group, subsets, mlcm, Accumulator, join, printf)
          
          # the cards
          cards = list(irange(1, 12))
          
          # map cards to their digit sum, and number of digits
          dsum = dict((x, enigma.dsum(x)) for x in cards)
          ndigits = dict((x, enigma.ndigits(x)) for x in cards)
          
          # find maximum arrangement of cards in ss
          def find_max(ss):
            d = mlcm(*ss)
            even = any(x % 2 == 0 for x in ss)
            # look for max rearrangement
            r = Accumulator(fn=max)
            fn = (lambda x: (lambda x: (-len(x), x))(str(x)))
            for s in subsets(sorted(ss, key=fn, reverse=1), size=len, select="P"):
              if even and s[-1] % 2 != 0: continue
              # done, if leading digits are less than current max
              if r.value and s[0] != r.data[0] and str(s[0]) < str(r.value): break
              # form the number
              n = int(join(s))
              if n % d == 0: r.accumulate_data(n, s)
            return (r.value, r.data)
          
          # reject impossible subsets
          def check(ss):
            # look for impossible combinations
            if (5 in ss or 10 in ss) and (4 in ss or 8 in ss or 12 in ss): return False
            # calculate the sum of the digits
            ds = sum(dsum[x] for x in ss)
            # check for divisibility by 9
            if (9 in ss) and ds % 9 != 0: return False
            # check for divisibility by 3
            if (3 in ss or 6 in ss or 12 in ss) and ds % 3 != 0: return False
            # looks OK
            return True
          
          # sort subsets of cards into the total number of digits
          d = group(subsets(cards, min_size=1), st=check, by=(lambda ss: sum(ndigits[x] for x in ss)))
          
          r = Accumulator(fn=max)
          for k in sorted(d.keys(), reverse=1):
            printf("[considering {k} digits ...]")
          
            for ss in d[k]:
              rs = find_max(ss)
              if rs is None: continue
              r.accumulate_data(*rs)
          
            if r.value: break
          
          printf("max = {r.value} [{s}]", s=join(r.data, sep=","))
          

          Like

    • GeoffR's avatar

      GeoffR 2:30 pm on 10 December 2021 Permalink | Reply

      In this first solution, I assumed it was reasonable for the largest number to start with the digits 9,8,7 to minimise a solution run-time. It also found the seven possible solutions for Liam’s numbers from which the maximum can be found.

      from enigma import Timer
      timer = Timer('ST2843', timer='E')
      timer.start()
      
      from itertools import permutations
      
      # assume number from cards is ABCDEFGHIJ, with A = 9, B = 8 and C = 7
      # Also no digit in A..J is 5 or 10 - see previous postings
      cards = set((1, 2, 3, 4, 6, 7, 8, 9, 11, 12))
      
      # Assume first three digits must be 9, 8 and 7 to maximise Liam's number
      A, B, C = 9, 8, 7
      a, b, c = str(A), str(B), str(C)
      
      cards2 = cards.difference([A, B, C])
      
      Liam_nums = []
      
      # permute remainder of cards
      for p1 in permutations(cards2, 7):
        D, E, F, G, H, I, J = p1
        d, e, f, g = str(D), str(E), str(F), str(G)
        h, i, j = str(H), str(I), str(J)
        num = int(a + b + c + d + e + f + g + h + i + j)
        if all(num % d == 0 for d in (A, B, C, D, E, F, G, H, I, J)):
          if num not in Liam_nums:
            Liam_nums.append(num)
      
      # find largest number in the list
      print (f"Largest possible number = { max(Liam_nums)}")
      timer.stop()      
      timer.report()
      
      # Largest possible number = 987362411112
      #[ST2843] total time: 0.0151168s (15.12ms)
      
      print(Liam_nums)
      # There are only seven possible numbers in Liam's list:
      # [987162411312, 987111312264, 987241136112, 987211614312,
      #  987341621112, 987362411112, 987113624112]
      
      
      

      In the second solution, I did a full permutation solution for the 12 cards, which had an expected longer run-time, as there were over 6,300 potential numbers in the list.

      
      from enigma import Timer
      timer = Timer('ST2843', timer='E')
      timer.start()
      
      from itertools import permutations
      
      # Assume digits 5 & 10 not included (previous postings)
      # Assume 10-digit number is ABCDEFGHIJ
      cards = set((1, 2, 3, 4, 6, 7, 8, 9, 11, 12))
      
      Liam_nums = []
      
      for p1 in permutations(cards):
        A, B, C, D, E, F, G, H, I, J = p1
        a, b, c = str(A), str(B), str(C)
        d, e, f, g = str(D), str(E), str(F), str(G)
        h, i, j = str(H), str(I), str(J)
        num = int(a + b + c + d + e + f + g + h + i + j)
        if all(num % d == 0 for d in (A, B, C, D, E, F, G, H, I, J)):
          if num not in Liam_nums:
            Liam_nums.append(num)
      
      # find largest number in the list
      print (f"Largest possible number = { max(Liam_nums)}")
      timer.stop()      
      timer.report()
      
      #Largest possible number = 987362411112
      #[ST2843] total time: 9.1977548s (9.20s)
      
      

      Like

  • Unknown's avatar

    Jim Randell 10:00 am on 7 December 2021 Permalink | Reply
    Tags: by: Bryan Thwaites   

    Brain-Teaser 889: Counting the hours 

    From The Sunday Times, 20th August 1978 [link]

    At school the other day, little Johnny was working with one of those boards with twelve clock-points regularly spaced round a circle against which should be put twelve counters showing the hours.

    He was, in fact, in a bit of a daze about the whole thing and the only hour he was absolutely dead sure of was 12 whose counter he correctly placed. As for the eleven others, if the truth be told, he just put them around at random.

    But Jill, his teacher, spotted some curious things. She first noticed that, however she chose a quartet of counters which formed the corners of a square, their sum was always the same.

    Next, she saw that if she formed numbers by multiplying together the counters at the corners of each square, one of those numbers was more than six times one of the others.

    She also observed that the counters in each quartet were, starting at the lowest, in ascending order of magnitude in the clockwise direction, and that 12 was not the only correct counter.

    In break, she reported all this to her colleague, Mary, adding “If I were to tell you, in addition, how many hours apart from the 12 Johnny had got right, you could tell me which they were”.

    Which were they?

    This puzzle is included in the book The Sunday Times Book of Brain-Teasers: Book 1 (1980). The puzzle text above is taken from the book.

    [teaser889]

     
    • Jim Randell's avatar

      Jim Randell 10:01 am on 7 December 2021 Permalink | Reply

      There are three squares that can be constructed, using the numbers in positions (12, 3, 6, 9), (1, 4, 7, 10), (2, 5, 8, 11). These partition the 12 numbers into 3 sets of 4.

      The total sum of the numbers is T(12) = 78, so values for each set must sum to 78/3 = 26.

      The following Python program runs in 48ms. (Internal runtime is 680µs).

      Run: [ @replit ]

      from enigma import (irange, subsets, diff, ediv, tuples, multiply, cproduct, filter_unique, unpack, printf)
      
      # find viable layouts
      def generate():
        ns = list(irange(1, 12))
        T = sum(ns)
        t = ediv(T, 3)
      
        # choose 3 numbers to go with 12 (and they must be in ascending order)
        n12 = 12
        for (n3, n6, n9) in subsets(diff(ns, [n12]), size=3):
          s1 = (n3, n6, n9, n12)
          if sum(s1) != t: continue
          p1 = multiply(s1)
      
          # choose numbers for (1, 4, 7, 10)
          for s2 in subsets(diff(ns, s1), size=4):
            if sum(s2) != t: continue
            p2 = multiply(s2)
      
            # remaining numbers
            s3 = diff(ns, s1 + s2)
            p3 = multiply(s3)
      
            # one of the products must be more than 6 times one of the others
            if not (max(p1, p2, p3) > 6 * min(p1, p2, p3)): continue
      
            # assign s1 to (1, 4, 7, 10) and s2 to (2, 5, 8, 11)
            fn = lambda s: tuples(s, 4, circular=1)
            for ((n1, n4, n7, n10), (n2, n5, n8, n11)) in cproduct([fn(s2), fn(s3)]):
              # construct the arrangement
              vs = [n1, n2, n3, n4, n5, n6, n7, n8, n9, n10, n11, n12]
              # find the numbers in the correct positions
              ss = tuple(n for (i, n) in enumerate(vs, start=1) if i == n)
              # there should be more than 1
              if len(ss) > 1:
                yield (vs, ss)
      
      # knowing len(ss) allows you to determine ss
      r = filter_unique(generate(), unpack(lambda vs, ss: len(ss)), unpack(lambda vs, ss: ss))
      
      # output solutions
      for (vs, ss) in r.unique:
        printf("{vs} -> {ss}")
      

      Solution: Johnny also placed 4 and 10 in the correct positions (as well as 12).

      There are two positions that lead to this:

      They both have squares with values (1, 2, 11, 12), (3, 4, 9, 10), (5, 6, 7, 8). But in the second one the (5, 6, 7, 8) square is rotated through 180°.

      The sums of the squares are all 26, and the products are (264, 1080, 1680), and 1680 > 1584 = 6 × 264.


      We find there are 14 possible arrangements that give the situation described.

      10 of them have 12 plus either 5, 7, or 8 in the correct position.

      2 of them have 12 plus (4, 5, 10) or (4, 8, 10) in the correct position.

      And the remaining two are those shown above with 12 plus (4, 10) in the correct position.

      Like

      • Frits's avatar

        Frits 9:22 am on 8 December 2021 Permalink | Reply

        @Jim, you also could have used decompose() to find 4 numbers which sum to “t”.

        Like

    • GeoffR's avatar

      GeoffR 7:50 pm on 7 December 2021 Permalink | Reply

      # four square group positions are (12,3,6,9), (1,4,7,10), (2,5,8,11)
      # sum of digits (1-12) = 78, so sum of each group is 26
      
      hours = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
      H12 = 12   # set correct counter for Hour 12
      
      from itertools import permutations
      
      # 1st square group positions (12,3,6,9)
      for p1 in permutations(hours, 3):
        # counters for hours H3, H6 and H9
        H3, H6, H9 = p1  
        if H3 + H6 + H9 + H12 != 26:continue
        if not (H3 < H6 < H9 < H12):continue
        q1 = hours.difference([H3, H6, H9])
        
        # 2nd  square group positions (1,4,7,10)
        for p2 in permutations(q1, 4):
          # counters for hours H1, H4, H7, H9
          H1, H4, H7, H10 = p2
          if H1 +  H4 + H7 + H10 != 26:continue
          if not (H1 < H4 < H7 < H10):continue  
          q2 = hours.difference(p1).difference(p2)
          
          # 3rd square group positions (2,5,8,11)
          for p3 in permutations(q2,4):
            # counters for hours H2, H5, H8, H11
            H2, H5, H8, H11 = p3
            if H2 + H5 + H8 + H11 != 26:continue
            if not (H2 < H5 < H8 < H11):continue
            
            # find multiples of the corners of three groups
            m1 = H3 * H6 * H9 * H12
            m2 = H1 * H4 * H7 * H10
            m3 = H2 * H5 * H8 * H11
            m1, m3 = min([m1, m2, m3]), max([m1, m2, m3])
            if m1 < m2 < m3:
              # check one multiple is more than 6X another multiple
              if m2 > 6 * m1 or m3 > 6 * m1:
                print(f" Three products are {m1}, {m2}, and {m3}.")
                print(f" (H1, H2, H3) = ({H1}, {H2}, {H3})")
                print(f" (H4, H5, H6) = ({H4}, {H5}, {H6})")
                print(f" (H7, H8, H9) = ({H7}, {H8}, {H9})")
                print(f" (H10, H11, H12) = ({H10}, {H11}, {H12})")
      
      # Three products are 264, 1080, and 1680.
      # (H1, H2, H3) = (3, 5, 1)
      # (H4, H5, H6) = (4, 6, 2)
      # (H7, H8, H9) = (9, 7, 11)
      # (H10, H11, H12) = (10, 8, 12)
      # Only counters for hours 4, 10 and 12 are in the correct position.
      
      
      
      

      Like

    • GeoffR's avatar

      GeoffR 9:21 am on 8 December 2021 Permalink | Reply

      
      % A Solution in MiniZinc
      include "globals.mzn";
      
      % sum of digits 1..12 = 78, sum of each of three squares = 26
      % counter was correctly placed for 12 o'clock
      int: H12 == 12; 
      
      % Hour values
      var 1..11: H1; var 1..11: H2; var 1..11: H3; var 1..11: H4;
      var 1..11: H5; var 1..11: H6; var 1..11: H7; var 1..11: H8;
      var 1..11: H9; var 1..11: H10; var 1..11: H11; 
      
      constraint all_different ([H1,H2,H3,H4,H5,H6,H7,H8,H9,H10,H11,H12]);
      
      % Corners sum for 1st square  (positions 12,3,6,9)
      constraint H12 + H3 + H6 + H9 == 26;
      constraint H3 < H6 /\ H6 < H9 /\ H9 < H12;
      
      % Corners sum for 2nd square  (positions 1,4,7,10)
      constraint H1 + H4 + H7 + H10 == 26;
      constraint H1 < H4 /\ H4 < H7 /\ H7 < H10;
      
      % Corners sum for 3rd square  (positions 2,5,8,11)
      constraint H2 + H5 + H8 + H11 == 26;
      constraint H2 < H5 /\ H5 < H8 /\ H8 < H11;
      
      % Multiples of corner values - (sum 4 corners = 26, av < 7),
      % LB = 1*2*3*4 = 24, UB approx 7^4 = 2401, say 2400 
      var 24..2400:m1; var 24..2400:m2; var 24..2400:m3; 
      
      constraint m1 == H3 * H6 * H9 * H12;
      constraint m2 == H1 * H4 * H7 * H10;
      constraint m3 == H2 * H5 * H8 * H11;
      
      constraint m1 < m2 /\ m2 < m3;
      % one of the multiples was more than six times one of the others
      constraint m2 > 6 * m1 \/ m3 > 6 * m1;
      
      solve satisfy;
      
      % H12 = 12 << Hour 12 correct - stated value
      
      % H1 = 3;
      % H2 = 5;
      % H3 = 1;
      % H4 = 4;   << Hour 4 correct
      % H5 = 6;
      % H6 = 2;
      % H7 = 9;
      % H8 = 7;
      % H9 = 11;
      % H10 = 10;  << Hour 10 correct
      % H11 = 8;
      % m1 = 264;
      % m2 = 1080;
      % m3 = 1680;
      % % time elapsed: 0.15 s
      % ----------
      % ==========
      % Finished in 182msec
      
      

      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