AMPL Matrix of Varying Sized Sets Generation - set

I have a question related to AMPL. I'm trying to construct a matrix of sets, named A in the following code (part of the .mod file). This gives an error message of "A is already defined."
Please note that S, T are parameters and B is a set in .dat file. (They have already been read by the previous part of the .mod file that I excluded in the following code.)
set A{s in 1..S, t in 1..T} default {};
for {s in 1..S} {
for {t in 1..T} {
/*set A{s,t} default {};*/
for {sprime in 1..S: sprime != s}{
if B[sprime,t] = B[s,t] then {
let A[s,t] := A[s,t] union {sprime};
}
}
}
}
I tried commenting out the first line and uncommenting the 4th line; however, it did not help.
In short, what I'm trying to do is to have an empty A matrix sized SxT and then fill/update each element of that matrix with nested for loops. So, every element of the matrix will contain a set. The sizes of these elements/sets can be different.

I tested the following code and it seems to do what you wanted, without error messages:
reset;
param S := 5;
param T := 3;
model;
param B{1..S,1..T};
data;
param B: 1 2 3 :=
1 1 2 3
2 2 3 2
3 0 0 3
4 1 1 1
5 3 2 3
;
model;
set A{s in 1..S, t in 1..T} default {};
for {s in 1..S}{
for {t in 1..T}{
for {sprime in 1..S: sprime != s}{
if B[sprime,t] = B[s,t] then {
let A[s,t] := A[s,t] union {sprime}};
}
}
}
I haven't significantly modified the part that you posted, just added some definitions so it's self-contained. However, I do have a "reset" at the beginning of the script.
Is it possible that you forgot to clear definitions of A in between runs? If so, then you would get an "A is already defined" error, not because of the LET statements but because of the "set A" statement at the start of your code snippet.

Related

Answering the Longest Substring Without Repeating Characters in Kotlin

I've spend some time working on the problem and got this close
fun lengthOfLongestSubstring(s: String): Int {
var set = HashSet<Char>()
var initalChar = 0
var count = 0
s.forEach {r ->
while(!set.add(s[r]))
set.remove(s[r])
initalChar++
set.add(s[r])
count = maxOf(count, r - initialChar + 1)
}
return count
}
I understand that a HashSet is needed to answer the question since it doesn't allow for repeating characters but I keep getting a type mismatch error. I'm not above being wrong. Any assistance will be appreciated.
Your misunderstanding is that r represents a character in the string, not an index of the string, so saying s[r] doesn't make sense. You just mean r.
But you are also using r on its own, so you should be using forEachIndexed, which lets you access both the element of the sequence and the index of that element:
s.forEach { i, r ->
while(!set.add(r))
set.remove(r)
initialChar++
set.add(r)
count = maxOf(count, i - initialChar + 1)
}
Though there are still some parts of your code that doesn't quite make sense.
while(!set.add(r)) set.remove(r) is functionally the same as set.add(r). If add returns false, that means the element is already in the set, you remove it and the next iteration of the loop adds the element back into the set. If add returns true, that means the set didn't have the element and it was successfully added, so in any case, the result is you add r to the set.
And then you do set.add(r) again two lines later for some reason?
Anyway, here is a brute-force solution that you can use as a starting point to optimise:
fun lengthOfLongestSubstring(s: String): Int {
val set = mutableSetOf<Char>()
var currentMax = 0
// for each substring starting at index i...
for (i in s.indices) {
// update the current max from the previous iterations...
currentMax = maxOf(currentMax, set.size)
// clear the set to record a new substring
set.clear()
// loop through the characters in this substring
for (j in i..s.lastIndex) {
if (!set.add(s[j])) { // if the letter already exists
break // go to the next iteration of the outer for loop
}
}
}
return maxOf(currentMax, set.size)
}

How does lazyness of the slice index affects the slicing of an array/list? [RAKU]

When we slice an array with an index that exceeds the boundaries of the array we get as the result the undefined (Any)
When we pass the same slice index as a lazy list then we get as result the existing values of the array/list (and NOT any more than that):
my #a = ^5;
say #a[^10]; # (0 1 2 3 4 (Any) (Any) (Any) (Any) (Any))
say #a[lazy ^10]; # (0 1 2 3 4)
It is clear that lazyness of the slice index affects the result.
Trying to undestand the way things are and as a proof of concept I programmed my simple version of the slice mechanism:
my #a = ^5;
my #s1 = ^10;
my #s2 = lazy ^10;
sub postcircumfix:<-[ ]-> (#container, #index) {
my $iter = #index.iterator;
gather {
loop {
my $item := $iter.pull-one;
if $item =:= IterationEnd {
last;
}
with #container[$item] {
take #container[$item]
} else {
#index.is-lazy ?? { last } !! take #container[$item];
}
}
}
}
say #a-[#s1]-; # (0 1 2 3 4 (Any) (Any) (Any) (Any) (Any))
say #a-[#s2]-; # (0 1 2 3 4)
But I am wondering if my naive algorithm depicts the way that things are computed under the hood !
The source for how things are done under the hood can be found in array_slice.pm6.
Specifically, you can see the following at L73:
if is-pos-lazy {
# With lazy indices, we truncate at the first one that fails to exists.
my \rest-seq = Seq.new(pos-iter).flatmap: -> Int() $i {
nqp::unless(
$eagerize($i),
last,
$i
)
};
my \todo := nqp::create(List::Reifier);
nqp::bindattr(todo, List::Reifier, '$!reified', eager-indices);
nqp::bindattr(todo, List::Reifier, '$!current-iter', rest-seq.iterator);
nqp::bindattr(todo, List::Reifier, '$!reification-target', eager-indices);
nqp::bindattr(pos-list, List, '$!todo', todo);
}
else {
pos-iter.push-all: target;
}
So, as you've surmised, it does indeed stop after a list item doesn't exist. This is no doubt becaue many lazy lists are infinite, and iterators don't provide a way to know if they are infinite or not (the generator may be non-determinative).
If you really want to enable such a thing, you could, for instance, write your own slicer that handles lazy lists where an element may not be available, but you have to take care to ensure that things are only eagerly evaluated if you know they're finite:
multi sub postcircumfix:<-[ ]-> (#a, #b) {
lazy gather {
take #a[$_] for #b;
}
}
my #a = ^5;
my #b = lazy gather { 
for ^10 -> $i { 
# So we can track when elements are evaluated
say "Generated \#b[$i]";
take $i;
}
};
say "Are we lazy? ", #a-[#b]-;
say "Let's get eager: ", #a-[#b]-.eager;
say "Going beyond indices: ", #a-[#b]-[11]
The output of this is
Are we lazy? (...)
Generated #b[0]
Generated #b[1]
Generated #b[2]
Generated #b[3]
Generated #b[4]
Generated #b[5]
Generated #b[6]
Generated #b[7]
Generated #b[8]
Generated #b[9]
Let's get eager: (0 1 2 3 4 (Any) (Any) (Any) (Any) (Any))
Going beyond indices: Nil

Weird map read issue?

I have a map I need to read with an iterator loop, and this map reads with this loop in another section of my program, but for whatever reason, using this loop at another part doesn't let me read the last key of the map.
Here is an abstracted version of it:
cout<<map.size()<<endl;
for(auto it = map.begin(); it != map.end(); ++it)
{
cout<<it->first<<endl;
}
Sample output:
4
a
b
c
d
Yet if I use this in another portion of code, the output is:
4
a
b
c
Any idea why this could be?

How to count lines including the ending new lines?

I have been searching online for a long time and there is no correct answer as far as I can find. Now the most common answer looks like below:
int main() {
int number_of_lines = 0;
std::string line;
std::ifstream myfile("textexample.txt");
while (std::getline(myfile, line))
++number_of_lines;
std::cout << "Number of lines in text file: " << number_of_lines;
return 0;
}
If the textexample.txt file actually has two empty lines at the end, this program will only count one of them, I'm guessing the first one. Such as below:
1
2
3
4
5
6
The above 6 numbers and 3 empty lines are 9 lines in total, but the program above will return 8.
I don't know why, but it seems std::getline() only loops 8 times.
The file in your example has 10 lines, of which 3 are empty. And if I run your code (with the missing includes...) it tells me there are 10 lines. So either you're running different code, or you're mis-quoting the file. Or you C++ standard library is broken somehow...
If I remove the line with "end", I get 9, not 8, lines.

Range of doubles in Swift

I am currently writing a Swift application and parts of it require making sure certain user inputs add up to a specified value.
A simplified example:
Through program interaction, the user has specified that totalValue = 67 and that turns = 2. This means that in two inputs, the user will have to provide two values that add up to 67.
So lets say on turn 1 the user enters 32, and then on turn 2 he enters 35, this would be valid because 32 + 35 = 67.
This all works fine, but the moment we verge into more than one decimal place, the program cannot add the numbers correctly. For example, if totalValue = 67 and then on turn 1 the user enters 66.95 and then on turn 2 he enters .05 the program will return that this is an error despite the fact that
66.95 + .05 = 67. This problem does not happen with one decimal place or less (something like turn 1 = 55.5 and turn 2 = 11.5 works fine), only for two decimal spots and beyond. I am storing the values as doubles. Thanks in advance
Some example code:
var totalWeights = 67
var input = Double(myTextField.text.bridgeToObjectiveC().doubleValue)
/*Each turn is for a button click*/
/*For turn 1*/
if inputValid == true && turn == 1 && input < totalWeights
{
myArray[0] = input
}
else
{
//show error string
}
/*For turn 2*/
if inputValid == true && turn == 2 && input == (totalWeights - myArray[0])
{
myArray[1] = input
}
else
{
//show error string
}
If you want exact values from floating point then the float/double types will not work, as they are only ever approximations of exact numbers. Look into using the NSDecimalNumber class from within Swift, I'm not sure what the bridging would look like but it should be simple.
Here is an example of how this could work:
var a = 0
for num in numlist {
a += num
}
var result = false
if a == targetnum
result = true
I haven't tested this out, but if numlist is an array of double then it should work for any input that is a valid number.
One problem I just realized is that there is an issue with doing an equals with doubles, as rounding will cause problems for you. I am not going to show it, but if, while reading in the inputs you keep track of how many numbers to the right of the decimal place, then multiply all of the values by that number of tens, so 66.95 * 100 to get it all as an integer, then add, then do the comparison, after multiplying the targetnum by the same value (100).
Unfortunately there is no ideal solution to this. We must use approximation type comparison.
For example, instead of checking:
if val1 == val2
we must try something like:
if val1 > (val2 - .0005) && val1 < (val2 + .0005)

Resources