I have this small code:
param n, integer, > 0; # number of clients
param m, integer, > 0; # number of facilities
param g, integer, > 0;
set I := 1..n;
set J := 1..m;
set G := 1..g;
param d{i in I, j in J};/* distance for client i to factory j*/
param w{i in I, j in J};/* distance for client i to factory j*/
param l{j in J}; # distance from factory j to factory 1
param F{j in J}; # cost of open a factory in J
param s{i in I, g in G};
The problem is on the s, it always says drdrd.mod:13: syntax error in literal set , if I change the g in G for j in J, everything is ok. Is not possible to have 3 differents sets?
And another question I could not solve, if I put instead of i in I, 2 in I (because I want to take into account the first 2 numbers ) it says also the same error message.
Thanks for your time.
g is defined as a parameter in
param g, integer, > 0;
so you can't use it as an index name in
param s{i in I, g in G};
To fix this rename the index (or parameter):
param s{i in I, gg in G};
Related
I have read some tutorials on Binary Indexed Tree, but i'm not able to understand how to implement it when query and update both operations are in some range.
To implement range update and range query, you need to know about range update and point query ( update [a,b] with v; query(x) gives the value at A[x]).
We'll use two BIT's to implement range update and range query.
Let's say the array is initialized to 0. If we update [a,b] with v,
For some x, sum(0,x) = 0 if 0 < x < a
= v*(x - (a-1)) if a <= x <= b
= v * (b - (a-1)) if b < x
where v is the value at A[x] (calculated via BIT1)
From the above formula, we'll find T, when subtracted from v*x (v is calculated from BIT1) we get the result.
if 0 < x < a : sum(0,x) = 0, T = 0
a <= x <= b: sum(0,x) = v*x - v*(a-1) , T = v*(a-1)
b < x : sum(0,x) = v*(b-a+1) , T = -v*(b-(a-1)) (since A[x] = 0 when x > b)
We store T in second BIT (BIT2)
Now, to implement update [a,b] with v:
update(a,v) ; update(b+1,-v) in BIT1 and
update(a,v*(a-1)); update(b+1,-v*b) in BIT2
sum[0,x]:
QueryBIT1(x)*x - QueryBIT2(x); // call query() on corresponding BIT
where, update(index,value) and Query(index) are implementations that are used for point update and range query.
For, further details:
http://zobayer.blogspot.in/2013/11/various-usage-of-bit.html
https://kartikkukreja.wordpress.com/2013/12/02/range-updates-with-bit-fenwick-tree/
I have been tried to do the Morris Pratt table and the code is basically this one in C:
void preMp(char *x, int m, int mpNext[]) {
int i, j;
i = 0;
j = mpNext[0] = -1;
while (i < m) {
while (j > -1 && x[i] != x[j])
j = mpNext[j];
mpNext[++i] = ++j;
}
}
and here is where i get so far in Fortran
program MP_ALGORITHM
implicit none
integer, parameter :: m=4
character(LEN=m) :: x='abac'
integer, dimension(4) :: T
integer :: i, j
i=0
T(1)=-1
j=-1
do while(i < m)
do while((j > -1) .AND. (x(i+1:i+1) /= (x(j+i+1:j+i+1))))
j=T(j)
end do
i=i+1
j=j+1
T(i)=j
end do
print *, T(1:)
end program MP_ALGORITHM
and the problem is i think i am having the wrong output.
for x=abac it should be (?):
a b a c
-1 0 1 0
and my code is returning 0 1 1 1
so, what i've done wrong?
The problem here is that C indices start from zero, but Fortran indices start from one. You can try to adjust the index for every array acces by one, but this will get unwieldy.
The Morris-Pratt table itself is an array of indices, so it should look different in C and Fortran: The Fortran array should have one-based indices and it should use zero as invalid index.
Together with the error that chw21 pointed out, your function might look like this:
subroutine kmp_table(x, t)
implicit none
character(*), intent(in) :: x
integer, dimension(:), intent(out) :: t
integer m
integer :: i, j
m = len(x)
i = 1
t(1) = 0
j = 0
do while (i < m)
do while(j > 0 .and. x(i:i) /= x(j:j))
j = t(j)
end do
i = i + 1
j = j + 1
t(i) = j
end do
end subroutine
You can then use it in the Morris-Pratt algorithm as taken straight from the Wikipedia page with adjustment for Fortran indices:
function kmp_index(S, W) result(res)
implicit none
integer :: res
character(*), intent(in) :: S ! text to search
character(*), intent(in) :: W ! word to find
integer :: m ! zero-based offset in S
integer :: i ! one-based offset in W and T
integer, dimension(len(W)) :: T ! KMP table
call kmp_table(W, T)
i = 1
m = 0
do while (m + i <= len(S))
if (W(i:i) == S(m + i:m + i)) then
if (i == len(W)) then
res = m + 1
return
end if
i = i + 1
else
if (T(i) > 0) then
m = m + i - T(i)
i = T(i)
else
i = 1
m = m + 1
end if
end if
end do
res = 0
end function
(The index m is zero-based here, because t is only ever used in conjunction with i in S(m + i:m + i). Adding two one-based indices will yield an offset of one, whereas keeping m zero-based makes this a neutral addition. m is a local variable that isn't exposed to code from the outside.)
Alternatively, you could make your Fortran arrays zero-based by specifying a lower bound of zero for your string and array. That will clash with the useful character(*) notation, though, which always uses one-based indexing. In my opinion, it is better to think about the whole algorithm in the typical one-based indexing scheme of Fortran.
this site isn't really a debugging site. Normally I would suggest you have a look at how to debug code. It didn't take me very long to go through your code with a pen and paper and verify that that is indeed the table it produces.
Still, here are a few pointers:
The C code compares x[i] and x[j], but you compare x[i] and x[i+j] in your Fortran code, more or less.
Integer arrays usually also start at index 1 in Fortran. So just like adding one to the index in the x String, you also need to add 1 every time you access T anywhere.
I have written the MAX-HEAPIFY(A,i) method from the introduction to algorithms book. Now I want to write it without recursion using while loop. Can you help me please?
You can use while loop with condition your i <= HEAPSIZE and using all other same conditions , except when you find the right position just break the loop.
Code:-
while ( i < = heapsize) {
le <- left(i)
ri <- right(i)
if (le<=heapsize) and (A[le]>A[i])
largest <- le
else
largest <- i
if (ri<=heapsize) and (A[ri]>A[largest])
largest <- ri
if (largest != i)
{
exchange A[i] <-> A[largest]
i <- largest
}
else
break
}
The solution above works but I think that following code is closer to the recursive version
(* Code TP compatible *)
const maxDim = 1000;
type TElem = integer;
TArray = array[1..maxDim]of TElem
procedure heapify(var A:TArray;i,heapsize:integer);
var l,r,largest,save:integer;
temp:TElem;
(*i - index of node that violates heap property
l - index of left child of node with index i
r - index of right child of node with index i
largest - index of largest element of the triplet (i,l,r)
save - auxiliary variable to save the value of i
temp - auxiliary variable used for swapping *)
begin
repeat
l:=2*i;
r:=2*i + 1;
if(l <= heapsize) and (A[l] > A[i]) then
largest:=l
else
largest:=i;
if(r <= heapsize) and (A[r] > A[largest]) then
largest:=r;
(*Now we save the value i to check properly the termination
condition of repeat until loop
The value of i will be modified soon in the if statement *)
save:=i;
if largest <> i then
begin
temp:=A[i];
A[i]:=A[largest];
A[largest]:=temp;
i:=largest;
end;
until largest = save;
(*Why i used repeat until istead of while ?
because body of the called procedure will be executed
at least once *)
end;
One more thing, in Wirth's Algorithms + Data Structures = Programs
can be found sift procedure without recursion but we should introduce boolean variable or break to eliminate goto statement
A lot of people at Facebook like to play Starcraft II™. Some of them have made a custom game using the Starcraft II™ map editor. In this game, you play as the noble Protoss defending your adopted homeworld of Shakuras from a massive Zerg army. You must do as much damage to the Zerg as possible before getting overwhelmed. You can only build two types of units, shield generators and warriors. Shield generators do no damage, but your army survives for one second per shield generator that you build. Warriors do one damage every second. Your army is instantly overrun after your shield generators expire. How many shield generators and how many warriors should you build to inflict the maximum amount of damage on the Zerg before your army is overrun? Because the Protoss value bravery, if there is more than one solution you should return the one that uses the most warriors.
Constraints
1 ≤ G (cost for one shield generator) ≤ 100
1 ≤ W (cost for one warrior) ≤ 100
G + W ≤ M (available funds) ≤ 1000000000000 (1012)
Here's a solution whose complexity is O(W). Let g be the number of generators we build, and similarly let w be the number of warriors we build (and G, W be the corresponding prices per unit).
We note that we want to maximize w*g subject to w*W + g*G <= M.
First, we'll get rid of one of the variables. Note that if we choose a value for g, then obviously we should buy as many warriors as possible with the remaining amount of money M - g*G. In other words, w = floor((M-g*G)/W).
Now, the problem is to maximize g*floor((M-g*G)/W) subject to 0 <= g <= floor(M/G). We want to get rid of the floor, so let's consider W distinct cases. Let's write g = W*k + r, where 0 <= r < W is the remainder when dividing g by W.
The idea is now to fix r, and insert the expression for g and then let k be the variable in the equation. We'll get the following quadratic equation in k:
Let p = floor((M - r*G)/W), then the equation is (-GW) * k^2 + (Wp - rG)k + rp.
This is a quadratic equation which goes to negative infinity when x goes to infinity or negative infinity so it has a global maximum at k = -B/(2A). To find the maximum value for legal values of k, we'll try the minimum legal value of k, the maximum legal value of k and the two nearest integer points of the real maximum if they are within the legal range.
The overall maximum for all values of r is the one we are seeking. Since there are W values for r, and it takes O(1) to compute the maximum for a fixed value, the overall time is O(W).
If you build g generators, and w warriors, you can do a total damage of
w (damage per time) × g (time until game-over).
The funds constraint restricts the value of g and w to W × w + G × g ≤ M.
If you build g generators, you can build at most (M - g × G)/W warriors, and do g × (M - g × G)/W damage.
This function has a maximum at g = M / (2 G), which results in M2 / (4 G W) damage.
Summary:
Build M / (2 G) shield generators.
Build M / (2 G) warriors.
Do M2 / (4 G W) damage.
Since you can only build integer amounts of any of the two units, this reduces to the optimization problem:
maximize g × w
with respect to g × G + w × W ≤ M and g, w ∈ ℤ+
The general problem of Integer Programming is NP-complete, so the best algorithm for this is to check all integer values close to the real-valued solution above.
If you find some pair (gi, wi), with total damage di, you only have to check values where gj × wj ≥ di. This and the original condition W × w + G × g ≤ M constrains the search-space with each item found.
F#-code:
let findBestSetup (G : int) (W : int) (M : int) =
let mutable bestG = int (float M / (2.0 * float G))
let mutable bestW = int (float M / (2.0 * float W))
let mutable bestScore = bestG * bestW
let maxW = (M + isqrt (M*M - 4 * bestScore * G * W)) / (2*G)
let minW = (M - isqrt (M*M - 4 * bestScore * G * W)) / (2*G)
for w = minW to maxW do
// ceiling of (bestScore / w)
let minG = (bestScore + w - 1) / w
let maxG = (M - W*w)/G
for g = minG to maxG do
let score = g * w
if score > bestScore || score = bestScore && w > bestW then
bestG <- g
bestW <- w
bestScore <- score
bestG, bestW, bestScore
This assumed W and G were the counts and the cost of each was equal to 1. So it's obsolete with the updated question.
Damage = LifeTime*DamagePerSecond = W * G
So you need to maximize W*G with the constraint G+W <= M. Since both Generators and Warriors are always good we can use G+W = M.
Thus the function we want to maximize becomes W*(M-W).
Now we set the derivative = 0:
M-2W=0
W = M/2
But since we need the solution to the discrete case(You can't have x.5 warriors and x.5 generators) we use the values closest to the continuous solution(this is optimal due to the properties of a parabel).
If M is even than the continuous solution is identical to the discrete solution. If M is odd then we have two closest solutions, one with one warrior more than generators, and one the other way round. And the OP said we should choose more warriors.
So the final solution is:
G = W = M/2 for even M
and G+1 = W = (M+1)/2 for odd M.
g = total generators
gc = generator cost
w = warriors
wc = warrior cost
m = money
d = total damage
g = (m - (w*wc))/gc
w = (m - (g*gc))/wc
d = g * w
d = ((m - (w*wc))/gc) * ((m - (g*gc))/wc)
d = ((m - (w*wc))/gc) * ((m - (((m - (w*wc))/gc)*gc))/wc) damage as a function of warriors
I then tried to compute an array of all damages then find max but of course it'd not complete in 6 mins with m in the trillions.
To find the max you'd have to differentiate that equation and find when it equals zero, which I forgotten how to do seing I haven't done math in about 6 years
Not a really a solution but here goes.
The assumption is that you already get a high value of damage when the number of shields equals 1 (cannot equal zero or no damage will be done) and the number of warriors equals (m-g)/w. Iterating up should (again an assumption) reach the point of compromise between the number of shields and warriors where damage is maximized. This is handled by the bestDamage > calc branch.
There is almost likely a flaw in this reasoning and it'd be preferable to understand the maths behind the problem. As I haven't practised mathematics for a while I'll just guess that this requires deriving a function.
long bestDamage = 0;
long numShields = 0;
long numWarriors = 0;
for( int k = 1;; k++ ){
// Should move declaration outside of loop
long calc = m / ( k * g ); // k = number of shields
if( bestDamage < calc ) {
bestDamage = calc;
}
if( bestDamage > calc ) {
numShields = k;
numWarriors = (m - (numShields*g))/w;
break;
}
}
System.out.println( "numShields:" + numShields );
System.out.println( "numWarriors:" + numWarriors );
System.out.println( bestDamage );
Since I solved this last night, I thought I'd post my C++ solution. The algorithm starts with an initial guess, located at the global maximum of the continuous case. Then it searches 'little' to the left/right of the initial guess, terminating early when continuous case dips below an already established maximum. Interestingly, the 5 example answers posted by the FB contained 3 wrong answers:
Case #1
ours: 21964379805 dmg: 723650970382348706550
theirs: 21964393379 dmg: 723650970382072360271 Wrong
Case #2
ours: 1652611083 dmg: 6790901372732348715
theirs: 1652611083 dmg: 6790901372732348715
Case #3
ours: 12472139015 dmg: 60666158566094902765
theirs: 12472102915 dmg: 60666158565585381950 Wrong
Case #4
ours: 6386438607 dmg: 10998633262062635721
theirs: 6386403897 dmg: 10998633261737360511 Wrong
Case #5
ours: 1991050385 dmg: 15857126540443542515
theirs: 1991050385 dmg: 15857126540443542515
Finally the code (it uses libgmpxx for large numbers). I doubt the code is optimal, but it does complete in 0.280ms on my personal computer for the example input given by FB....
#include <iostream>
#include <gmpxx.h>
using namespace std;
typedef mpz_class Integer;
typedef mpf_class Real;
static Integer getDamage( Integer g, Integer G, Integer W, Integer M)
{
Integer w = (M - g * G) / W;
return g * w;
}
static Integer optimize( Integer G, Integer W, Integer M)
{
Integer initialNg = M / ( 2 * G);
Integer bestNg = initialNg;
Integer bestDamage = getDamage ( initialNg, G, W, M);
// search left
for( Integer gg = initialNg - 1 ; ; gg -- ) {
Real bestTheoreticalDamage = gg * (M - gg * G) / (Real(W));
if( bestTheoreticalDamage < bestDamage) break;
Integer dd = getDamage ( gg, G, W, M);
if( dd >= bestDamage) {
bestDamage = dd;
bestNg = gg;
}
}
// search right
for( Integer gg = initialNg + 1 ; ; gg ++ ) {
Real bestTheoreticalDamage = gg * (M - gg * G) / (Real(W));
if( bestTheoreticalDamage < bestDamage) break;
Integer dd = getDamage ( gg, G, W, M);
if( dd > bestDamage) {
bestDamage = dd;
bestNg = gg;
}
}
return bestNg;
}
int main( int, char **)
{
Integer N;
cin >> N;
for( int i = 0 ; i < N ; i ++ ) {
cout << "Case #" << i << "\n";
Integer G, W, M, FB;
cin >> G >> W >> M >> FB;
Integer g = optimize( G, W, M);
Integer ourDamage = getDamage( g, G, W, M);
Integer fbDamage = getDamage( FB, G, W, M);
cout << " ours: " << g << " dmg: " << ourDamage << "\n"
<< " theirs: " << FB << " dmg: " << fbDamage << " "
<< (ourDamage > fbDamage ? "Wrong" : "") << "\n";
}
}
Is there a one line expression (possibly boolean) to get the nearest 2^n number for a given integer?
Example: 5,6,7 must be 8.
Round up to the next higher power of two: see bit-twiddling hacks.
In C:
unsigned int v; // compute the next highest power of 2 of 32-bit v
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
I think you mean next nearest 2^n number. You can do a log on the mode 2 and then determine next integer value out of it.
For java, it can be done like:
Math.ceil(Math.log(x)/Math.log(2))
Since the title of the question is "Round to the nearest power of two", I thought it would be useful to include a solution to that problem as well.
int nearestPowerOfTwo(int n)
{
int v = n;
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++; // next power of 2
int x = v >> 1; // previous power of 2
return (v - n) > (n - x) ? x : v;
}
It basically finds both the previous and the next power of two and then returns the nearest one.
Your requirements are a little confused, the nearest power of 2 to 5 is 4. If what you want is the next power of 2 up from the number, then the following Mathematica expression does what you want:
2^Ceiling[Log[2, 5]] => 8
From that it should be straightforward to figure out a one-liner in most programming languages.
For next power of two up from a given integer x
2^(int(log(x-1,2))+1)
or alternatively (if you do not have a log function accepting a base argument
2^(int(log(x-1)/log(2))+1)
Note that this does not work for x < 2
This can be done by right shifting on the input number until it becomes 0 and keeping the count of shifts. This will give the position of the most significant 1 bit. Getting 2 to the power of this number will give us the next nearest power of 2.
public int NextPowerOf2(int number) {
int pos = 0;
while (number > 0) {
pos++;
number = number >> 1;
}
return (int) Math.pow(2, pos);
}
For rounding up to the nearest power of 2 in Java, you can use this. Probably faster for longs than the bit-twiddling stuff mentioned in other answers.
static long roundUpToPowerOfTwo(long v) {
long i = Long.highestOneBit(v);
return v > i ? i << 1 : i;
}
Round n to the next power of 2 in one line in Python:
next_power_2 = 2 ** (n - 1).bit_length()
Modified for VBA. NextPowerOf2_1 doesn't seem to work. So I used loop method. Needed a shift right bitwise operator though.
Sub test()
NextPowerOf2_1(31)
NextPowerOf2_2(31)
NextPowerOf2_1(32)
NextPowerOf2_2(32)
End Sub
Sub NextPowerOf2_1(ByVal number As Long) ' Does not work
Debug.Print 2 ^ (Int(Math.Log(number - 1) / Math.Log(2)) + 1)
End Sub
Sub NextPowerOf2_2(ByVal number As Long)
Dim pos As Integer
pos = 0
While (number > 0)
pos = pos + 1
number = shr(number, 1)
Wend
Debug.Print 2 ^ pos
End Sub
Function shr(ByVal Value As Long, ByVal Shift As Byte) As Long
Dim i As Byte
shr = Value
If Shift > 0 Then
shr = Int(shr / (2 ^ Shift))
End If
End Function
Here is a basic version for Go
// Calculates the next highest power of 2.
// For example: n = 15, the next highest power of 2 would be 16
func NearestPowerOf2(n int) int {
v := n
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
}