Back to Or Tools

dudeney

examples/notebook/contrib/dudeney.ipynb

2016-062.6 KB
Original Source
Copyright 2025 Google LLC.

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.

dudeney

<table align="left"> <td> <a href="https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/dudeney.ipynb">Run in Google Colab</a> </td> <td> <a href="https://github.com/google/or-tools/blob/main/examples/contrib/dudeney.py">View source on GitHub</a> </td> </table>

First, you must install ortools package in this colab.

python
%pip install ortools
python
# Copyright 2010 Pierre Schaus ([email protected])
# 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.
from ortools.constraint_solver import pywrapcp


def dudeney(n):
  solver = pywrapcp.Solver('Dudeney')
  x = [solver.IntVar(list(range(10)), 'x' + str(i)) for i in range(n)]
  nb = solver.IntVar(list(range(3, 10**n)), 'nb')
  s = solver.IntVar(list(range(1, 9 * n + 1)), 's')

  solver.Add(nb == s * s * s)
  solver.Add(sum([10**(n - i - 1) * x[i] for i in range(n)]) == nb)
  solver.Add(sum([x[i] for i in range(n)]) == s)

  solution = solver.Assignment()
  solution.Add(nb)
  collector = solver.AllSolutionCollector(solution)

  solver.Solve(
      solver.Phase(x, solver.INT_VAR_DEFAULT, solver.INT_VALUE_DEFAULT),
      [collector])

  for i in range(collector.SolutionCount()):
    nbsol = collector.Value(i, nb)
    print(nbsol)

  print('#fails:', solver.Failures())
  print('time:', solver.WallTime(), 'ms')


dudeney(6)