I am trying to solve a facility location problem. This is my code:
set S;
param prod{i in S};
param distri{i in S};
param fixed{i in S};
param cap{i in S};
param demand{i in S};
var x{i in S, j in S}, >= 0;
var y{i in S}, binary;
minimize obj :
sum{i in S} fixed[i]*y[i] +
sum{i in S, j in S} x[i,j]*(prod[i] + distri[i])*y[i];
s.t. c1{i in S}:
sum{j in S} x[i,j]*y[i] <= cap[i];
s.t. c2{i in S}:
sum{j in S} x[j,i]*y[j] = demand[i];
display S;
solve;
printf '\n Solution: \nMinimum Cost = %.2f\n', obj;
display x;
display y;
data;
set S := 0 1 2 3;
param prod :=
0 20
1 30
2 40
3 50;
param distri :=
0 60
1 70
2 80
3 90;
param fixed :=
0 10
1 15
2 10
3 15;
param cap :=
0 100
1 110
2 120
3 130;
param demand :=
0 120
1 60
2 70
3 100;
end;
When I run this .mod file, I get the following error:
example.mod:13: multiplication of linear forms not allowed
Context: S } x [ i , j ] * ( prod [ i ] + distri [ i ] ) * y [ i ] ;
MathProg model processing error
Here x is the fractional demand provided by facility 'i' for client 'j'.
I removed y[i] from the line mentioned and the error was gone. But if I do that, I get the same multiplication error but this time in c1 constraint.
What is the correct approach? Thank you.
gplk is restricted to linear problems.
It is allowed to multiply parameters and variables. But products of variables are non-linear. You either have to rewrite the model or use a non-linear solver.
Linearization of products involving a binary variable is discussed in this related answer.
Related
I've been racking my brain for a couple of days to work out a series or closed-form equation to the following problem:
Specifically: given all strings of length N that draws from an alphabet of L letters (starting with 'A', for example {A, B}, {A, B, C}, ...), how many of those strings contain a substring that matches the pattern: 'A', more than 1 not-'A', 'A'. The standard regular expression for that pattern would be A[^A][^A]+A.
The number of possible strings is simple enough: L^N . For small values of N and L, it's also very practical to simply create all possible combinations and use a regular expression to find the substrings that match the pattern; in R:
all.combinations <- function(N, L) {
apply(
expand.grid(rep(list(LETTERS[1:L]), N)),
1,
paste,
collapse = ''
)
}
matching.pattern <- function(N, L, pattern = 'A[^A][^A]+A') {
sum(grepl(pattern, all.combinations(N, L)))
}
all.combinations(4, 2)
matching.pattern(4, 2)
I had come up with the following, which works for N < 7:
M <- function(N, L) {
sum(
sapply(
2:(N-2),
function(g) {
(N - g - 1) * (L - 1) ** g * L ** (N - g - 2)
}
)
)
}
Unfortunately, that only works while N < 7 because it's simply adding the combinations that have substrings A..A, A...A, A....A, etc. and some combinations obviously have multiple matching substrings (e.g., A..A..A, A..A...A), which are counted twice.
Any suggestions? I am open to procedural solutions too, so long as they don't blow up with the number of combinations (like my code above would). I'd like to be able to compute for values of N from 15 to 25 and L from 2 to 10.
For what it is worth, here's the number of combinations, and matching combinations for some values of N and L that are tractable to determine by generating all combinations and doing a regular expression match:
N L combinations matching
-- - ------------ --------
4 2 16 1
5 2 32 5
6 2 64 17
7 2 128 48
8 2 256 122
9 2 512 290
10 2 1024 659
4 3 81 4
5 3 243 32
6 3 729 172
7 3 2187 760
8 3 6561 2996
9 3 19683 10960
10 3 59049 38076
4 4 256 9
5 4 1024 99
6 4 4096 729
7 4 16384 4410
8 4 65536 23778
9 4 262144 118854
10 4 1048576 563499
It is possible to use dynamic programming approach.
For fixed L, let X(n) be number of strings of length n that contain given pattern, and let A(n) be number of strings of length n that contain given pattern and starts with A.
First derive recursion formula for A(n). Lets count all strings in A(n) by grouping them by first 2-3 letters. Number of strings in A(n) with:
"second letter A" is A(n-1),
"second letter non-A and third letter is A" is A(n-2),
"second and third letter non-A" is (L^(n-3) - (L-1)^(n-3)). That is because string 'needs' at least one A in remaining letters to be counted.
With that:
A(n) = A(n-1) + (L-1) * (A(n-2) + (L-1) * (L^(n-3) - (L-1)^(n-3)))
String of length n+1 can start with A or non-A:
X(n+1) = A(n+1) + (L-1) * X(n)
X(i) = A(i) = 0, for i <= 3
Python implementation:
def combs(l, n):
x = [0] * (n + 1) # First element is not used, easier indexing
a = [0] * (n + 1)
for i in range(4, n+1):
a[i] = a[i-1] + (l-1) * (a[i-2] + (l-1) * (l**(i-3) - (l-1)**(i-3)))
x[i] = a[i] + (l-1) * x[i-1]
return x[4:]
print(combs(2, 10))
print(combs(3, 10))
print(combs(4, 10))
This can be described as a state machine. (For simplicity, x is any letter other than A.)
S0 := 'A' S1 | 'x' S0 // ""
S1 := 'A' S1 | 'x' S2 // A
S2 := 'A' S1 | 'x' S3 // Ax
S3 := 'A' S4 | 'x' S3 // Axx+
S4 := 'A' S4 | 'x' S4 | $ // AxxA
Counting the number of matching strings of length n
S0(n) = S1(n-1) + (L-1)*S0(n-1); S0(0) = 0
S1(n) = S1(n-1) + (L-1)*S2(n-1); S1(0) = 0
S2(n) = S1(n-1) + (L-1)*S3(n-1); S2(0) = 0
S3(n) = S4(n-1) + (L-1)*S3(n-1); S3(0) = 0
S4(n) = S4(n-1) + (L-1)*S4(n-1); S4(0) = 1
Trying to reduce S0(n) to just n and L gives a really long expression, so it would be easiest to calculate the recurrence functions as-is.
For really large n, this could be expressed as a matrix expression, and be efficiently calculated.
n
[L-1 1 0 0 0 ]
[ 0 1 L-1 0 0 ] T
[0 0 0 0 1] × [ 0 1 0 L-1 0 ] × [1 0 0 0 0]
[ 0 0 0 L-1 1 ]
[ 0 0 0 0 L ]
In JavaScript:
function f(n, L) {
var S0 = 0, S1 = 0, S2 = 0, S3 = 0, S4 = 1;
var S1_tmp;
while (n-- > 0) {
S0 = S1 + (L - 1) * S0;
S1_tmp = S1 + (L - 1) * S2;
S2 = S1 + (L - 1) * S3;
S3 = S4 + (L - 1) * S3;
S4 = S4 + (L - 1) * S4;
S1 = S1_tmp;
}
return S0;
}
var $tbody = $('#resulttable > tbody');
for (var L = 2; L <= 4; L++) {
for (var n = 4; n <= 10; n++) {
$('<tr>').append([
$('<td>').text(n),
$('<td>').text(L),
$('<td>').text(f(n,L))
]).appendTo($tbody);
}
}
#resulttable td {
text-align: right;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="resulttable">
<thead>
<tr>
<th>N</th>
<th>L</th>
<th>matches</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Triangular numbers are numbers which is number of things when things can be arranged in triangular shape.
For Example, 1, 3, 6, 10, 15... are triangular numbers.
o o o o o o o o o o is shape of n=4 triangular number
what I have to do is A natural number N is given and I have to print
N expressed by sum of triangular numbers.
if N = 4
output should be
1 1 1 1
1 3
3 1
else if N = 6
output should be
1 1 1 1 1 1
1 1 1 3
1 1 3 1
1 3 1 1
3 1 1 1
3 3
6
I have searched few hours and couldn't find answers...
please help.
(I am not sure this might help, but I found that
If i say T(k) is Triangular number when n is k, then
T(k) = T(k-1) + T(k-3) + T(k-6) + .... + T(k-p) while (k-p) > 0
and p is triangular number )
Here's Code for k=-1(Read comments below)
#include <iostream>
#include <vector>
using namespace std;
long TriangleNumber(int index);
void PrintTriangles(int index);
vector<long> triangleNumList(450); //(450 power raised by 2 is about 200,000)
vector<long> storage(100001);
int main() {
int n, p;
for (int i = 0; i < 450; i++) {
triangleNumList[i] = i * (i + 1) / 2;
}
cin >> n >> p;
cout << TriangleNumber(n);
if (p == 1) {
//PrintTriangles();
}
return 0;
}
long TriangleNumber(int index) {
int iter = 1, out = 0;
if (index == 1 || index == 0) {
return 1;
}
else {
if (storage[index] != 0) {
return storage[index];
}
else {
while (triangleNumList[iter] <= index) {
storage[index] = ( storage[index] + TriangleNumber(index - triangleNumList[iter]) ) % 1000000;
iter++;
}
}
}
return storage[index];
}
void PrintTriangles(int index) {
// What Algorithm?
}
Here is some recursive Python 3.6 code that prints the sums of triangular numbers that total the inputted target. I prioritized simplicity of code in this version. You may want to add error-checking on the input value, counting the sums, storing the lists rather than just printing them, and wrapping the entire routine into a function. Setting up the list of triangular numbers could also be done in fewer lines of code.
Your code saved time but worsened memory usage by "memoizing" the triangular numbers (storing and reusing them rather than always calculating them when needed). You could do the same to the sum lists, if you like. It is also possible to make this more in the dynamic programming style: find the sum lists for n=1 then for n=2 etc. I'll leave all that to you.
""" Given a positive integer n, print all the ways n can be expressed as
the sum of triangular numbers.
"""
def print_sums_of_triangular_numbers(prefix, target):
"""Print sums totalling to target, each after printing the prefix."""
if target == 0:
print(*prefix)
return
for tri in triangle_num_list:
if tri > target:
return
print_sums_of_triangular_numbers(prefix + [tri], target - tri)
n = int(input('Value of n ? '))
# Set up list of triangular numbers not greater than n
triangle_num_list = []
index = 1
tri_sum = 1
while tri_sum <= n:
triangle_num_list.append(tri_sum)
index += 1
tri_sum += index
# Print the sums totalling to n
print_sums_of_triangular_numbers([], n)
Here are the printouts of two runs of this code:
Value of n ? 4
1 1 1 1
1 3
3 1
Value of n ? 6
1 1 1 1 1 1
1 1 1 3
1 1 3 1
1 3 1 1
3 1 1 1
3 3
6
It's about this dynamic programming challenge.
If you have a hard time to understand the Problem then see also on AbhishekVermaIIT's post
Basically, you get as input an array B and you construct array A. Fo this array A you need the maximum possible sum with absolute(A[i] - A[i-1]), for i = 1 to N. How to construct array A? --> You can choose for every element A[i] in array A either the values 1 or B[i]. (As you will deduce from the problem description any other value between these two values doesn't make any sense.)
And I came up with this recursive Java solution (without memoization):
static int costHelper(int[] arr, int i) {
if (i < 1) return 0;
int q = max(abs(1 - arr[i-1]) + costHelper(arr, i-1) , abs(arr[i] - arr[i-1]) + costHelper(arr, i-1));
int[] arr1 = new int[i];
for (int j = 0; j < arr1.length-1; j++) {
arr1[j] = arr[j];
}
arr1[i-1] = 1;
int r = max(abs(1 - 1) + costHelper(arr1, i-1) , abs(arr[i] - 1) + costHelper(arr1, i-1));
return max(q , r);
}
static int cost(int[] arr) {
return costHelper(arr, arr.length-1);
}
public static void main(String[] args) {
int[] arr = {55, 68, 31, 80, 57, 18, 34, 28, 76, 55};
int result = cost(arr);
System.out.println(result);
}
Basically, I start at the end of the array and check what is maximizing the sum of the last element minus last element - 1. But I have 4 cases:
(1 - arr[i-1])
(arr[i] - arr[i-1])
(1 - 1) // I know, it is not necessary.
(arr[i] -1)
For the 3rd or 4th case I construct a new array one element smaller in size than the input array and with a 1 as the last element.
Now, the result of arr = 55 68 31 80 57 18 34 28 76 55 according to Hackerrank should be 508. But I get 564.
Since it has to be 508 I guess the array should be 1 68 1 80 1 1 34 1 76 1.
For other arrays I get the right answer. For example:
79 6 40 68 68 16 40 63 93 49 91 --> 642 (OK)
100 2 100 2 100 --> 396 (OK)
I don't understand what is wrong with this algorithm.
I'm not sure exactly what's happening with your particular solution but I suspect it might be that the recursive function only has one dimension, i, since we need a way to identify the best previous solution, f(i-1), both if B_(i-1) was chosen and if 1 was chosen at that point, so we can choose the best among them vis-a-vis f(i). (It might help if you could add a description of your algorithm in words.)
Let's look at the brute-force dynamic program: let m[i][j1] represent the best sum-of-abs-diff in A[0..i] when A_i is j1. Then, generally:
m[i][j1] = max(abs(j1 - j0) + m[i-1][j0])
for j0 in [1..B_(i-1)] and j1 in [1..B_i]
Python code:
def cost(arr):
if len(arr) == 1:
return 0
m = [[float('-inf')]*101 for i in xrange(len(arr))]
for i in xrange(1, len(arr)):
for j0 in xrange(1, arr[i-1] + 1):
for j1 in xrange(1, arr[i] + 1):
m[i][j1] = max(m[i][j1], abs(j1 - j0) + (m[i-1][j0] if i > 1 else 0))
return max(m[len(arr) - 1])
That works but times out since we are looping potentially 100*100*10^5 iterations.
I haven't thought through the proof for it, but, as you suggest, apparently we can choose only from either 1 or B_i for each A_i for an optimal solution. This allows us to choose between those directly in a significantly more efficient solution that won't time out:
def cost(arr):
if len(arr) == 1:
return 0
m = [[float('-inf')]*2 for i in xrange(len(arr))]
for i in xrange(1, len(arr)):
for j0 in [1, arr[i-1]]:
for j1 in [1, arr[i]]:
a_i = 0 if j1 == 1 else 1
b_i = 0 if j0 == 1 else 1
m[i][a_i] = max(m[i][a_i], abs(j1 - j0) + (m[i-1][b_i] if i > 1 else 0))
return max(m[len(arr) - 1])
This is a bottom-up tabulation but we could easily convert it to a recursive one using the same idea.
Here is the javascript code with memoization-
function cost(B,n,val) {
if(n==-1){
return 0;
}
let prev1=0,prev2=0;
if(n!=0){
if(dp[n-1][0]==-1)
dp[n-1][0] = cost(B,n-1,1);
if(dp[n-1][1]==-1)
dp[n-1][1] = cost(B,n-1,B[n]);
prev1=dp[n-1][0];
prev2=dp[n-1][1];
}
prev1 = prev1 + Math.abs(val-1);
prev2 = prev2+ Math.abs(val-B[n]);
return Math.max(prev1,prev2);
}
where B->given array,n->total length,val-> 1 or B[n], value considered by the calling function.
Initial call -> Math.max(cost(B,n-2,1),cost(B,n-2,B[n-1]));
BTW, this took me around 3hrs, rather could have easily done with iteration method. :p
//dp[][0] is when a[i]=b[i]
dp[i][0]=max((dp[i-1][0]+abs(b[i]-b[i-1])),(dp[i-1][1]+abs(b[i]-1)));
dp[i][1]=max((dp[i-1][1]+abs(1-1)),(dp[i-1][0]+abs(b[i-1]-1)));
Initially all the elements in dp have the value of 0.
We know that we will get the answer if at any i the value is b[i] or 1. So the final answer is :
max(dp[n-1][0],dp[n-1][1])
dp[i][0] signifies a[i]=b[i] and dp[i][1] signifies a[i]=1.
So at every i we want the maximum of [i-1][0] (previous element is b[i-1]) or [i-1][1] (previous element is 1)
I have been experiencing a strange behaviour of a glpsol, more precisely one of its variables. I run the command using glpsol -m sol.mod
Input, in file sol.mod:
set Points := (1..3);
var a{i in Points}, >= 0;
var x1{i in Points};
var x2{i in Points};
maximize obj: sum{i in Points} a[i];
px1: x1[1] = 0;
py1: x2[1] = 0;
px2: x1[2] = 2;
py2: x2[2] = 1;
px3: x1[3] = 3;
py3: x2[3] = 3;
p1x2: x1[1] + a[1] <= x1[2] - a[2];
p1x3: x1[1] + a[1] <= x1[3] - a[3];
p2x3: x2[2] + a[2] <= x2[3] - a[3];
solve;
printf "#OUTPUT:\n";
#printf{i in Points} "a_%d = %d\n", i, a[i];
printf "a[1]: %d\n", a[1];
printf "-a[1]: %d\n", -a[1];
printf "a[3]: %d\n", a[3];
printf "#OUTPUT END:\n";
end;
Output:
GLPSOL: GLPK LP/MIP Solver, v4.52
Parameter(s) specified in the command line:
-m sol.mod
Reading model section from sol.mod...
22 lines were read
Generating obj...
Generating px1...
Generating py1...
Generating px2...
Generating py2...
Generating px3...
Generating py3...
Generating p1x2...
Generating p1x3...
Generating p2x3...
Model has been successfully generated
GLPK Simplex Optimizer, v4.52
10 rows, 9 columns, 21 non-zeros
Preprocessing...
3 rows, 3 columns, 6 non-zeros
Scaling...
A: min|aij| = 1.000e+00 max|aij| = 1.000e+00 ratio = 1.000e+00
Problem data seem to be well scaled
Constructing initial basis...
Size of triangular part is 3
* 0: obj = 0.000000000e+00 infeas = 0.000e+00 (0)
* 3: obj = 3.500000000e+00 infeas = 0.000e+00 (0)
OPTIMAL LP SOLUTION FOUND
Time used: 0.0 secs
Memory used: 0.1 Mb (126476 bytes)
#OUTPUT:
a[1]: 2
-a[1]: -1
a[3]: 2
#OUTPUT END:
Model has been successfully processed
The issue seems to be that a[1] is evaluated to 2, while -a[1] is evaluated to -1. Also the a[3] equals 2 as well, so the constraint p1x3 is not fulfilled.
Currently I have no idea how to fix this or even what caused it.
Change %d format specifier to %g and see what happens. Note that a{i} are continuous variables that may have fractional values.
The regular recursive approach for pow(x,n) is as follows:
pow (x,n):
= 1 ...n=0
= 0 ...x=0
= x ...n=1
= x * pow (x, n-1) ...n>0
With this approach 2^(37) will require 37 multiplications. How do I modify this to reduces the number of multiplications to less than 10? I think this could be done only if the function is not excessive.
With this approach you can compute 2^(37) with only 7 multiplications.
pow(x,n):
= 1 ... n=0
= 0 ... x=0
= x ... n=1
= pow(x,n/2) * pow (x,n/2) ... n = even
= x * pow(x,n/2) * pow(x,n.2) ... n = odd
Now lets calculate 2^(37) with this approach -
2^(37) =
= 2 * 2^(18) * 2^(18)
= 2^(9) * 2^(9)
= 2 * 2^(4) * 2^(4)
= 2^(2) * 2^(2)
= 2 * 2
This function is not excessive and hence it reuses the values once calculated. Thus only 7 multiplications are required to calculate 2^(37).
You can calculate the power of a number in logN time instead of linear time.
int cnt = 0;
// calculate a^b
int pow(int a, int b){
if(b==0) return 1;
if(b%2==0){
int v = pow(a, b/2);
cnt += 1;
return v*v;
}else{
int v = pow(a, b/2);
cnt += 2;
return v*v*a;
}
}
Number of multiplications will be 9 for the above code as verified by this program.
Doing it slightly differently than invin did, I come up with 8 multiplications. Here's a Ruby implementation. Be aware that Ruby methods return the result of the last expression evaluated. With that understanding, it reads pretty much like pseudo-code except you can actually run it:
$count = 0
def pow(a, b)
if b > 0
$count += 1 # note only one multiplication in both of the following cases
if b.even?
x = pow(a, b/2)
x * x
else
a * pow(a, b-1)
end
else # no multiplication for the base case
1
end
end
p pow(2, 37) # 137438953472
p $count # 8
Note that the sequence of powers with which the method gets invoked is
37 -> 36 -> 18 -> 9 -> 8 -> 4 -> 2 -> 1 -> 0
and that each arrow represents one multiplication. Calculating the zeroth power always yields 1, with no multiplication, and there are 8 arrows.
Since xn = (xn/2)2 = (x2)n/2 for even values of n, we can derive this subtly different implementation:
$count = 0
def pow(a, b)
if b > 1
if b.even?
$count += 1
pow(a * a, b/2)
else
$count += 2
a * pow(a * a, b/2)
end
elsif b > 0
a
else
1
end
end
p pow(2, 37) # 137438953472
p $count # 7
This version includes all of the base cases in the original question, it's easy to run and confirm that it calculates 2^37 in 7 multiplications, and doesn't require any allocation of local variables. For production use you would, of course, comment out or remove the references to $count.