How can I get sum of items that do not belong to a set in google or-tools - constraints

I am trying to implement equations containing these.
Sum not belongs to
These items are Boolean variable. So, if it is part of the solution it will set to 1 else it will be 0 after calling the solve method.
If it was the opposite (belongs to) then I would simple loop over all the items and after solving it, I would check if the variable is set to 1 or not.
I am using MIP solver with SCIP backend (C++)
std::unique_ptr<MPSolver> solver(MPSolver::CreateSolver("SCIP"));
std::vector<const MPVariable *> z(edges.size());
for (int e = 0; e < edges.size(); e++)
{
z[e] = solver->MakeBoolVar(absl::StrFormat("z_%d, %d", edges.at(e).at(0), edges.at(e).at(1)));
}
Here, z is Boolean variable
The way I get the sum
LinearExpr sum_z;
for (int e = 0; e < z.size(); e++)
{
sum_z += LinearExpr(z[e]);
}
I really cannot think of any way for this. Tried to search for "or-tools not belongs to set sum" in the google. No luck. Tried to find these in the examples of or-tools. Still no idea.
If you can give any hint or idea. Please share
Edit:
Attempt to subtract sum of z_e from size of z (equal to edges)
(LinearExpr(z.size()) - sum_z)
to check whether the value is true or not
for (int e = 0; e < z.size(); e++)
{
if (z[e]->solution_value() > 0)
{
// true
}
}
The expression is used to define constraints like this
Constraints
Here, E and V both are set of Boolean Variable. The complication in my situation is summing the elements not inside a set.

Related

RAD Studio 10.2 (C++): ~TControl() destructor only works on every second iteration

Whenever I try to run the ~TControl(); destructor on some child TPanel controls (components) that were created at runtime, it only destructs every second child Panel (e.g. see the code below).
for(int i=0; i < ParentPanel->ControlCount; i++)
{
ParentPanel->Controls[i]->~TControl();
}
It only destructs the remaining child TPanel controls if I run the 'for' loop again and again (I have no idea why).
Now if I try to program it to 'manually' destruct all the child controls that I know I'm going to create at runtime (let's say 4 child TPanel controls), it gives me a "List index out of bounds(#)" error, where # is half the total number of the controls that I construct and tell it to manually destruct.
ParentPanel->Controls[0]->~TControl();
ParentPanel->Controls[1]->~TControl();
ParentPanel->Controls[2]->~TControl();
ParentPanel->Controls[3]->~TControl();
e.g. The above would cause it to display a "List index out of bounds (2)" error.
The same thing happens even if I use the delete ParentPanel->Controls[0]; method instead.
Any clues? Your help is much appreciated. Thanks in advance.
Removing items from an indexed list should ideally be done backwards:
for (int i = ParentPanel->ControlCount - 1; i >= 0; i--)
{
delete ParentPanel->Controls[i];
}
The problem with counting up
Such lists usually shift all items "above" (with a higher index) down, so if Controls[i] was deleted, now a new control is moved to that index. But directly after, the index is incremented, so that it points to the item above the one that replaced the deleted one, and only that is removed. So, in effect, only every second item is removed.
Initially: [A] B C D E F G H I J i = 0
The index is indicated by [ ]
Now you delete and thus remove A, so the new order is:
[B] C D E F G H I J i = 0
But the loop immediately increments the index:
B [C] D E F G H I J i++, so i = 1
so in the next loop, C gets deleted (which means that B is skipped). And so on, and so forth. This means that only every second element gets removed.
But if you start at the top, no elements are being moved, so everything gets deleted.
Calling the destructor
It seems to me an extremely bad idea to call the destructor directly. Rather use delete.
Components
Note that if you want to remove all components, you should use the Components list and ComponentCount instead.
As #Axbor Axrorov said, it turned out to be the size of the array decreasing as each child control was destructed / deleted.
I found out that one way to do it was to use the decrement operator -- when deleting the child controls, so that as the integer in the 'for' loop increases, it keeps deleting the first element in the array as it continues to decrease in size (see code below).
for(int i=0; i<ParentPanel->ControlCount; i++)
{
if(ParentPanel->Controls[i] != NULL)
{
delete ParentPanel->Controls[i--];
}
}
You need to delete controls instead of calling destructor.
while(ParentPanel->ControlCount > 0)
delete ParentPanel->Controls[0];

Is there a way to write code in D similar to this Python expression?

There are articles and presentations about functional style programming in D (e.g. http://www.drdobbs.com/architecture-and-design/component-programming-in-d/240008321). I never used D before, but I'm interested in trying it. Is there a way to write code in D similar to this Python expression:
max(x*y for x in range(N) for y in range(x, N) if str(x*y) == str(x*y)[::-1])
Are there D constructs for generators or list (array) comprehensions?
Here's one possible solution, not particularly pretty:
iota(1,N)
.map!(x =>
iota(x,N)
.map!(y => tuple(x,y)))
.joiner
.map!(xy => xy[0]*xy[1])
.filter!(xy => equal(to!string(xy), to!string(xy).retro))
.reduce!max;
So what this actually does is create a range from 1 to N, and map each element to a range of tuples with your x,y values. This gives you a nested range ([[(1,1),(1,2)],[(2,2)]] for N = 2).
We then join this range to get a range of tuples ([(1,1),(1,2),(2,2)] for N = 2).
Next we map to x*y (D's map does for some reason not allow for unpacked tuples, so we need to use indexing).
Penultimately we filter out non-palindromes, before finally reducing the range to its largest element.
Simple answer, no, D does not have generators or list comprehensions (AFAIK). However, you can create a generator using an InputRange. For that solution, see this related question: What is a "yield return" equivalent in the D programming language?
However, your code isn't using generators, so your code could be translated as:
import std.algorithm : max, reduce, retro, equal;
import std.conv : to;
immutable N = 13;
void main() {
int[] keep;
foreach(x; 0 .. N) {
foreach(y; x .. N) {
auto val = x*y;
auto s = to!string(val);
if (equal(s, s.retro)) // reverse doesn't work on immutable Ranges
keep ~= val; // don't use ~ if N gets large, use appender instead
}
}
reduce!max(keep); // returns 121 (11*11)
}
For me, this is much more readable than your list comprehension because the list comprehension has gotten quite large.
There may be a better solution out there, but this is how I'd implement it. An added bonus is you get to see std.algorithm in all its glory.
However, for this particular piece of code, I wouldn't use the array to save on memory and instead store only the best value to save on memory. Something like this:
import std.algorithm : retro, equal;
import std.conv : to;
immutable N = 13;
void main() {
int best = 0;
foreach(x; 0 .. N) {
foreach(y; x .. N) {
auto val = x*y;
auto s = to!string(val);
if (equal(s, s.retro))
best = val;
}
}
}

How can I simply check if a set of n numbers are all different?

I have n integers and I need a quick logic test to see that they are all different, and I don't want to compare every combination to find a match...any ideas on a nice and elegant approach?
I don't care what programming language your idea is in, I can convert!
Use a set data structure if your language supports it, you might also look at keeping a hash table of seen elements.
In python you might try
seen={}
n_already_seen=n in seen
seen[n]=n
n_already_seen will be a boolean indicating if n has already been seen.
You don't have to check every combination thanks to commutivity and transitivity; you can simply go down the list and check each entry against each entry that comes after it. For example:
bool areElementsUnique( int[] arr ) {
for( int i=0; i<arr.Length-1; i++ ) {
for( int j=i+1; j<arr.Length; j++ ) {
if( arr[i] == arr[j] ) return false;
}
}
return true;
}
Note that the inner loop doesn't start from the beginning, but from the next element (i+1).
You can use a Hash Table or a Set type of data structure that using hashing. Then you can insert all of the elements into the hashtable or hashset, and either as you insert, check if the element is already in the table/set. If for some reason you don't want to check as you go, you can just insert all the numbers and then check to see if the size of the structure is less than n. If it is less than n, there had to be repeated elements. Otherwise, they were all unique.
Here is a really compact Java solution. The time-complexity is amortized O(n) and the space complexity is also O(n).
public boolean areAllElementsUnique(int [] list)
{
Set<Integer> set = new HashSet<Integer>();
for (int number: list)
if (set.contains(number))
return false;
else
set.add(number);
return true;
}

Basics in for loop in actionscript 3 in flex

Good Morning stackoverflow...
I'm having a problem.... this is my sample code
var i:Number = new Number();
trace("showarray length" + showArray.length);
for(i=0;i<showArray.length;i++){
trace("equal daw" + showArray.getItemAt(i).id + "==" + num);
if(showArray.getItemAt(i).id == num){
showArray.removeItemAt(i);
}
}
trace('alerts');
myproblem here is...wherenever the if is satisfied it stops looping it immediately goes out of the loop
this is a sample output
given that the length of showArray is 2 and num = 0
showarray length2
equal daw0==0
alerts
please help me
If you want to remove items while iterating over array, iterate in reverse order. This way element removal does not affect cycle condition:
for (var i:int = showArray.length - 1; i >= 0; i--) {
if (someCondition) {
showArray.removeItemAt(i);
}
}
Another small bonus that this is slightly faster, as it doesn't call showArray.length on each step.
An even better way might be to use the filter method of the Array class.
array = array.filter(function (e:*, i:int, a:Array):Boolean {
return e.id != num;
});
When your if is satisfied for id == num (which is 0 so happening in the first loop) and the item is removed, your array length decreases to 1 so the loop won't run any more.
That's because you are removing items at the time you are iterating throught them.
array = [1, 2]
^ // pointer in first iteration
eliminate 1
array = [2]
^ // the pointer remains in the same location
//ups! out of the loop. all items were visited.
You can copy the array before you iterate through it and iterate the copy or mark the indices to remove and remove them later or iterate the array backwards.
PS: Sorry for my poor English.
After showArray.removeItemAt(i);, add i--;
Because you removed the item at index i from the array, the item that was at i + 1 got moved to i. By subtracting one, you ensure that the moved item doesn't get skipped.
alxx's answer is also a good solution.

What are block expressions actually good for?

I just solved the first problem from Project Euler in JavaFX for the fun of it and wondered what block expressions are actually good for? Why are they superior to functions? Is it the because of the narrowed scope? Less to write? Performance?
Here's the Euler example. I used a block here but I don't know if it actually makes sense
// sums up all number from low to high exclusive which are divisible by a or b
function sumDivisibleBy(a: Integer, b: Integer, high: Integer) {
def low = if (a <= b) a else b;
def sum = {
var result = 0;
for (i in [low .. <high] where i mod a == 0 or i mod b == 0) {
result += i
}
result
}
}
Does a block make sense here?
Well, no, not really, it looks like extra complexity with no real benefit. Try removing the sum variable and the block and you will see that the code still works the same.
In general block expressions can be useful when you want to create an anonymous scope rather than factoring the code into a function, most of the time you should rather create a function.

Resources