Files
ortools-clone/examples/notebook/contrib/broken_weights.ipynb
2025-02-04 18:04:03 +01:00

220 lines
6.8 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"id": "google",
"metadata": {},
"source": [
"##### Copyright 2025 Google LLC."
]
},
{
"cell_type": "markdown",
"id": "apache",
"metadata": {},
"source": [
"Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"you may not use this file except in compliance with the License.\n",
"You may obtain a copy of the License at\n",
"\n",
" http://www.apache.org/licenses/LICENSE-2.0\n",
"\n",
"Unless required by applicable law or agreed to in writing, software\n",
"distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"See the License for the specific language governing permissions and\n",
"limitations under the License.\n"
]
},
{
"cell_type": "markdown",
"id": "basename",
"metadata": {},
"source": [
"# broken_weights"
]
},
{
"cell_type": "markdown",
"id": "link",
"metadata": {},
"source": [
"<table align=\"left\">\n",
"<td>\n",
"<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/broken_weights.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
"</td>\n",
"<td>\n",
"<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/broken_weights.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
"</td>\n",
"</table>"
]
},
{
"cell_type": "markdown",
"id": "doc",
"metadata": {},
"source": [
"First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "install",
"metadata": {},
"outputs": [],
"source": [
"%pip install ortools"
]
},
{
"cell_type": "markdown",
"id": "description",
"metadata": {},
"source": [
"\n",
"\n",
" Broken weights problem in Google CP Solver.\n",
"\n",
" From http://www.mathlesstraveled.com/?p=701\n",
" '''\n",
" Here's a fantastic problem I recently heard. Apparently it was first\n",
" posed by Claude Gaspard Bachet de Meziriac in a book of arithmetic problems\n",
" published in 1612, and can also be found in Heinrich Dorrie's 100\n",
" Great Problems of Elementary Mathematics.\n",
"\n",
" A merchant had a forty pound measuring weight that broke\n",
" into four pieces as the result of a fall. When the pieces were\n",
" subsequently weighed, it was found that the weight of each piece\n",
" was a whole number of pounds and that the four pieces could be\n",
" used to weigh every integral weight between 1 and 40 pounds. What\n",
" were the weights of the pieces?\n",
"\n",
" Note that since this was a 17th-century merchant, he of course used a\n",
" balance scale to weigh things. So, for example, he could use a 1-pound\n",
" weight and a 4-pound weight to weigh a 3-pound object, by placing the\n",
" 3-pound object and 1-pound weight on one side of the scale, and\n",
" the 4-pound weight on the other side.\n",
" '''\n",
"\n",
" Compare with the following problems:\n",
" * MiniZinc: http://www.hakank.org/minizinc/broken_weights.mzn\n",
" * ECLiPSE: http://www.hakank.org/eclipse/broken_weights.ecl\n",
" * Gecode: http://www.hakank.org/gecode/broken_weights.cpp\n",
" * Comet: http://hakank.org/comet/broken_weights.co\n",
"\n",
" This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
" Also see my other Google CP Solver models:\n",
" http://www.hakank.org/google_or_tools/\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "code",
"metadata": {},
"outputs": [],
"source": [
"import sys\n",
"\n",
"from ortools.constraint_solver import pywrapcp\n",
"\n",
"\n",
"def main(m=40, n=4):\n",
"\n",
" # Create the solver.\n",
" solver = pywrapcp.Solver('Broken weights')\n",
"\n",
" #\n",
" # data\n",
" #\n",
" print('total weight (m):', m)\n",
" print('number of pieces (n):', n)\n",
" print()\n",
"\n",
" #\n",
" # variables\n",
" #\n",
" weights = [solver.IntVar(1, m, 'weights[%i]' % j) for j in range(n)]\n",
" x = {}\n",
" for i in range(m):\n",
" for j in range(n):\n",
" x[i, j] = solver.IntVar(-1, 1, 'x[%i,%i]' % (i, j))\n",
" x_flat = [x[i, j] for i in range(m) for j in range(n)]\n",
"\n",
" #\n",
" # constraints\n",
" #\n",
"\n",
" # symmetry breaking\n",
" for j in range(1, n):\n",
" solver.Add(weights[j - 1] < weights[j])\n",
"\n",
" solver.Add(solver.SumEquality(weights, m))\n",
"\n",
" # Check that all weights from 1 to 40 can be made.\n",
" #\n",
" # Since all weights can be on either side\n",
" # of the side of the scale we allow either\n",
" # -1, 0, or 1 or the weights, assuming that\n",
" # -1 is the weights on the left and 1 is on the right.\n",
" #\n",
" for i in range(m):\n",
" solver.Add(i + 1 == solver.Sum([weights[j] * x[i, j] for j in range(n)]))\n",
"\n",
" # objective\n",
" objective = solver.Minimize(weights[n - 1], 1)\n",
"\n",
" #\n",
" # search and result\n",
" #\n",
" db = solver.Phase(weights + x_flat, solver.CHOOSE_FIRST_UNBOUND,\n",
" solver.ASSIGN_MIN_VALUE)\n",
"\n",
" search_log = solver.SearchLog(1)\n",
"\n",
" solver.NewSearch(db, [objective])\n",
"\n",
" num_solutions = 0\n",
" while solver.NextSolution():\n",
" num_solutions += 1\n",
" print('weights: ', end=' ')\n",
" for w in [weights[j].Value() for j in range(n)]:\n",
" print('%3i ' % w, end=' ')\n",
" print()\n",
" print('-' * 30)\n",
" for i in range(m):\n",
" print('weight %2i:' % (i + 1), end=' ')\n",
" for j in range(n):\n",
" print('%3i ' % x[i, j].Value(), end=' ')\n",
" print()\n",
" print()\n",
" print()\n",
" solver.EndSearch()\n",
"\n",
" print('num_solutions:', num_solutions)\n",
" print('failures :', solver.Failures())\n",
" print('branches :', solver.Branches())\n",
" print('WallTime:', solver.WallTime(), 'ms')\n",
"\n",
"\n",
"m = 40\n",
"n = 4\n",
"if len(sys.argv) > 1:\n",
" m = int(sys.argv[1])\n",
"if len(sys.argv) > 2:\n",
" n = int(sys.argv[2])\n",
"main(m, n)\n",
"\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
}
},
"nbformat": 4,
"nbformat_minor": 5
}