# Copyright 2021 Hakan Kjellerstrand hakank@gmail.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""

  Mrs Timkin's Age problem in OR-tools CP-SAT Solver.

  From 
  http://www.comp.nus.edu.sg/~henz/projects/puzzles/arith/index.html
  '''
  Mrs Timpkin's Age    from "Amusements in Mathematics, Dudeney", number 43.

  When the Timpkinses married eighteen years ago, Timpkins was three
  times as old as his wife, and today he is just twice as old as she.
  How old is Mrs. Timpkin? 
  '''

  Answer:
    Mr. Timpkin age: 72
    Mrs Timpkin age: 36


  This model was written by Hakan Kjellerstrand (hakank@gmail.com)
  See also my OR-tools page: http://hakank.org/or_tools/
"""
from __future__ import print_function
from ortools.sat.python import cp_model as cp
from cp_sat_utils import SimpleSolutionPrinter2


def main(married_years_ago_fixed=0):
    
  model = cp.CpModel()


  # variables
  t = model.NewIntVar(1,100,"Mr. Timpkin age")
  w = model.NewIntVar(1,100,"Mrs Timpkin age")
  
  # This could - of course - be a constant (18)
  # but it might interesting/funny/instructive 
  # to also let it be a decision variable.
  # Note that this will give non-legal (in legal terms)
  # marriages.
  married_years_ago = model.NewIntVar(0,100,"Married years ago")
  if married_years_ago_fixed > 0:
    model.Add(married_years_ago == married_years_ago_fixed)
    
  model.Add(t - married_years_ago == 3 * (w - married_years_ago))
  model.Add(t == 2*w)

  solver = cp.CpSolver()
  solution_printer = SimpleSolutionPrinter2([t,w,married_years_ago])
  status = solver.SearchForAllSolutions(model,solution_printer)

  if not status in [cp.OPTIMAL,cp.FEASIBLE]:
    print("No solution!")

  print()
  print("NumSolutions:", solution_printer.SolutionCount())  
  print("NumConflicts:", solver.NumConflicts())
  print("NumBranches:", solver.NumBranches())
  print("WallTime:", solver.WallTime())


if __name__ == '__main__':
  print("The stated puzzle:")
  main(18)
  print()
  print("No fixed marriage-when-ago age:")
  main()
