OR-Tools: An IntVar that is one IntVar minus another IntVar in Java? - or-tools

I'm using CP-SAT Solver in Java, and my objective is to minimize the range in the max and min values of an array of IntVars.
Creating IntVars for the max and min values in the array in Java is no problem. The challenge is creating the range IntVar in Java. In Python it's simple:
range = model.NewIntVar(1, 1000, "range")
model.Add(range == max - min)
model.Minimize(range)
I know that with OR-Tools in Java I need to use model.addEquality, instead of ==. But how to accomplish the subtraction to get the 'range' IntVar? I thought of using LinearExpr.sum on an IntVar[] containing max and the negative of min, where the negative of min comes from: LinearExpr.term(min, -1). But LinearExpr.term returns a LinearExpr, and LinearExpr.sum only accepts arrays of IntVars.
How can this be done in Java?

The cumbersome java way :-)
model.AddEquality(LinearExpr.Sum(new IntVar[] {x, y}), 1);
This is shown in the rabbit + pheasant sample.

Related

Microsoft SEAL : Required negative values as a result after subtraction of two PolyCRT composed ciphertexts

Suppose I have two vectors x = [1,2,3,4] and y = [5,1,2,6].
I composed and encrypted the two array using PolyCRTBuilder ( Ciphertextx and Ciphertexty ) .
If I subtract the two ciphertexts ( Ciphertextx MINUS Ciphertexty ), I should get Result = [-4, 1, 1, -2] but after the homomorphic subtraction I am getting ResultDecrypted = [40957, 1, 1, 40959] .
I understood that because the plaintext is only defined modulo plain_modulus, we got that result. But i want the resultant negative values to be used for the next computation how can i assign the resultant negative values to a vector and use the same for the further computations
You are using a pretty old version of SEAL if it still has PolyCRTBuilder; in newer versions of the library this has been renamed to BatchEncoder and it supports encoding to/from std::vector<std::int64_t> which, I believe, is what you want.

Is there a range data structure in Scala?

I'm looking for a way to handle ranges in Scala.
What I need to do is:
given a set of ranges and a range(A) return the range(B) where range(A) intersect range (B) is not empty
given a set of ranges and a range(A) remove/add range(A) from/to the set of ranges.
given range(A) and range(B) create a range(C) = [min(A,B), max(A,B)]
I saw something similar in java - http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/RangeSet.html
Though subRangeSet returns only the intersect values and not the range in the set (or list of ranges) that it intersects with.
RangeSet rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(0, 10));
rangeSet.add(Range.closed(30, 40));
Range range = Range.closed(12, 32);
System.out.println(rangeSet.subRangeSet(range)); //[30,32] (I need [30,40])
System.out.println(range.span(Range.closed(30, 40))); //[12,40]
There is an Interval[A] type in the spire math library. This allows working with ranges of arbitrary types that define an Order. Boundaries can be inclusive, exclusive or omitted. So e.g. (-∞, 0.0] or [0.0, 1.0) would be possible intervals of doubles.
Here is a library intervalset for working with sets of non-overlapping intervals (IntervalSeq or IntervalTrie) as well as maps of intervals to arbitrary values (IntervalMap).
Here is a related question that describes how to use IntervalSeq with DateTime.
Note that if the type you want to use is 64bit or less (basically any primitive), IntervalTrie is extremely fast. See the Benchmarks.
As Tzach Zohar has mentioned in the comment, if all you need is range of Int - go for scala.collection.immutable.Range:
val rangeSet = Set(0 to 10, 30 to 40)
val r = 12 to 32
rangeSet.filter(range => range.contains(r.start) || range.contains(r.end))
If you need it for another underlying type - implement it by yourself, it's easy for your usecase.

High-precision random numbers on iOS

I have been trying this for a while but thus far haven't had any luck.
What is the easiest way to retrieve a random number between two very precise numbers on iOS?
For example, I want a random number between 41.37783830549337 and 41.377730629131634, how would I accomplish this?
Thank you so much in advance!
Edit: I tried this:
double min = 41.37783830549337;
double max = 41.377730629131634;
double test = ((double)rand() / RAND_MAX) * (max - min) + min;
NSLog(#"Min:%lf, max:%lf, result:%lf",min,max,test);
But the results weren't quite as precise as I was hoping, and ended up like this::
Min:41.377838, max:41.377731, result:41.377838
You can normalise the output of rand to any range you want:
((double)rand() / RAND_MAX) * (max - min) + min
[Note: This is pure C, I'm assuming it works equivalently in Obj-C.]
[Note 2: Replace double with the data-type of your choice as appropriate.]
[Note 3: Replace rand with the random-number source of your choice as appropriate.]

How big can the argument to Perl's rand be?

rand(n) returns a number between 0 and n. Will rand work as expected, with regard to "randomness", for all arguments up to the integer limit on my platform?
This is going to depend on your randbits value:
rand calls your system's random number generator (or whichever one was
compiled into your copy of Perl). For this discussion, I'll call that
generator RAND to distinguish it from rand, Perl's function. RAND produces
an integer from 0 to 2**randbits - 1, inclusive, where randbits is a small
integer. To see what it is in your perl, use the command 'perl
-V:randbits'. Common values are 15, 16, or 31.
When you call rand with an argument arg, perl takes that value as an
integer and calculates this value.
arg * RAND
rand(arg) = ---------------
2**randbits
This value will always fall in the range required.
0 <= rand(arg) < arg
But as arg becomes large in comparison to 2**randbits, things become
problematic. Let's imagine a machine where randbits = 15, so RAND ranges
from 0..32767. That is, whenever we call RAND, we get one of 32768
possible values. Therefore, when we call rand(arg), we get one of 32768
possible values.
It depends on the number of bits used by your system's (pseudo)random number generator. You can find this value via
perl -V:randbits
or within a program via
use Config;
my $randbits = $Config{randbits};
rand can generate 2^randbits distinct random numbers. While you can generate numbers larger than 2^randbits, you can't generate all of the integer values in the range [0, N) when N > 2^randbits.
Values of N which aren't a power of two can also be problematic, as the distribution of (integer truncated) random values won't quite be flat. Some values will be slightly over-represented, others slightly under-represented.
It's worth noting that randbits is a paltry 15 on Windows. This means you can only get 32768 (2**15) distinct values. You can improve the situation by making multiple calls to rand and combining the values:
use Config;
use constant RANDBITS => $Config{randbits};
use constant RAND_MAX => 2**RANDBITS;
sub double_rand {
my $max = shift || 1;
my $iv =
int rand(RAND_MAX) << RANDBITS
| int rand(RAND_MAX);
return $max * ($iv / 2**(2*RANDBITS));
}
Assuming randbits = 15, double_rand mimics randbits = 30, providing 1073741824 (2**30) possible distinct values. This alleviates (but can never eliminate) both of the problems mentioned above.
We are talking about big random integers and whether it is possible to get them. It should be noted that the concatenation of two random integers is also a random integer. So if your system, for any reason, cannot go beyond 999999999999, then just write
$bigrand = int(rand(999999999999)).int(rand(999999999999));
and you'll get a random integer of (maximally) twice the length.
(Actually this is not a numeric answer to the question “how big a rand number can be” but rather the answer “you can get as big as you want, just concatenate small numbers”.)

How do I test if two dates are within a certain tolerance in NUnit?

How do I test if two dates are within a certain tolerance in NUnit?
You may want to look at the "Within" method that lives off of the Constraint object.
For example:
Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101));
It's usually used to give a tolerance to doubles and floats, but since in the end a DateTime is a double, it might suit your needs.
TimeSpan tolerance = new TimeSpan(0,1,0); // e.g. 1 minute
Assert.IsTrue((firstDateTime-SecondDateTime).Duration() > tolerance);
Convert your tolerance to Ticks and then use an And constraint. Something like;
long ticks = mydate.Ticks;
long tolerance = 1000;
Assert.That( ticks, Is.LessThan( ticks + tolerance ) & Is.GreaterThan( ticks - tolerance ) );
I would create an extension method or your own Assert to do this though.
Subtract one from the other, which gives you a TimeSpan value, use the TotalXYZ properties (like TotalMilliseconds) to get a value, use Math.Abs on it to convert it to a always-positive value, and check against your tolerance value.
For instance, if they need to be within 10 milliseconds of each other:
if (Math.Abs((dt1 - dt2).TotalMilliseconds) <= 10)
{
CloseEnough();
}