CP - OPL slicing input array - constraint-programming

I think I need some help with the OPL language :/
My code is the following:
using CP;
int NbMchs = ...;
range Mchs = 0..NbMchs-1;
tuple Mode {
int opId;
int mch;
int pt;
};
{Mode} Modes = ...;
// Not Working...
int test[m in Mchs] = all(md in Modes: md.mch == m) md.opId;
What I want to do is to extract m 1D arrays from the Modes structure containing just the opId field of the tuple. Each test[m] array has to contain it's corresponding elements: that is the opId field of the tuple md where md.mch =m.
The error that I get from the above code is "Cannot use type int[] for int". It seems like the right hand side of the above function is returning a single integer, but I was thinking that the all() operator is the one that I can use to do the job.
Thanks in advance

In the general case, the number of opId depends on the machine m so you cannot really have a 2-D array here. I would use an array of sets:
{int} test[m in Mchs] = { md.opId | md in Modes: md.mch == m };
Note that it assumes that you only have one mode per opId,mch.

Related

Assign an array to a property in a Chapel Class

Here is a Python-like pattern I need to re-create in Chapel.
class Gambler {
var luckyNumbers: [1..0] int;
}
var nums = [13,17,23,71];
var KennyRogers = new Gambler();
KennyRogers.luckyNumbers = for n in nums do n;
writeln(KennyRogers);
Produces the run-time error
Kenny.chpl:8: error: zippered iterations have non-equal lengths
I don't know how many lucky numbers Kenny will have in advance and I can't instantiate Kenny at that time. That is, I have to assign them later. Also, I need to know when to hold them, know when to fold them.
This is a good application of the array.push_back method. To insert lucky numbers one at a time you can do:
for n in nums do
KennyRogers.luckyNumbers.push_back(n);
You can also insert the whole array in a single push_back operation:
KennyRogers.luckyNumbers.push_back(nums);
There are also push_front and insert methods in case you need to put elements at the front or at arbitrary positions in the array.
I don't think I can help on when to hold them or when to fold them.
A way to approach this that simply makes things the right size from the start and avoids resizing/rewriting the array is to establish luckyNumbers in the initializer for Gambler. In order to do this without resizing, you'll need to declare the array's domain and set it in the initializer as well:
class Gambler {
const D: domain(1); // a 1D domain field representing the array's size
var luckyNumbers: [D] int; // declare lucky numbers in terms of that domain
proc init(nums: [?numsD] int) {
D = numsD; // make D a copy of nums's domain; allocates luckyNumbers to the appropriate size
luckyNumbers = nums; // initialize luckyNumbers with nums
super.init(); // mark the initialization of fields as being done
}
}
var nums = [13,17,23,71];
var KennyRogers = new Gambler(nums);
writeln(KennyRogers);

insert array into constructor Haskell

I have a function that return array of this form
[1.2,1.3,2.3]
and I created data:
data SpecielNumber = SP Float Float Float
How Can I from the foo function that returns the number to Generate SpecielNumber ?
something like this dont work :(
x=[1.2,1.3,2.3]
SP x
Thanks
First, [1.2, 1.3, 2.3] is not an array, its a list.
Second, your data type SpecialNumber needs a constructor name. So you can make it have a list in its constructor like this:
data SpecialNumber = SpecialNumber [Float]
The first SpecialNumber is the name of the type. The second is the name of the constructor. These are different name spaces. It is conventional to have the two match unless you are defining a type with different variants, like:
data Either a b = Left a | Right b
The Left and Right are alternative constructors, and the type is called Either.
hopefully, these will give some clues. You should read more...
> data SpecielNumber = SN Float Float Float deriving (Show)
> let makeSN [x,y,z] = SN x y z
> makeSN [1.2,1.3,2.3]
SN 1.2 1.3 2.3

How to get int from float in picat?

I try to to read a line as string from console (stdin) in picat and get its half:
main =>
L = read_line(),
B = L.length/2,
S = L.slice(1,B),
println(S).
crashes with error(integer_expected(2.0),slice)
when int used instead of B - no crash. So how to turn B into integer?
you could use built-in function such as floor, round or ceiling from math module (more functions here). So you could modify your code like this:
main =>
L = read_line(),
B = round(L.length/2),
S = L.slice(1,B),
println(S).
Try either using integer(..) function to convert L.length/2 to integer or use to_integer() function....should do it for you.
type inference plays an essential role in functional evaluation. (/ /2) it's a floating point arithmetic operator, but slice/2 expects an integer. So you should instead use (// /2).
Picat> L=read_line(),println(L.slice(1,L.length//2)).
123456789
1234
L = ['1','2','3','4','5','6','7','8','9']
yes

Data structure which supports fast starts_with and like operation on strings

Can you suggest me some data structures which will store about 100000 alpha numeric strings?Each string will have an integer X associated with it. The operations that it should efficiently support are :
starts_with(String s) -- return 10 strings that start with string s and have larger X value that other's. .
`like(String x,int start,int end)` -- return sublist(start,end-1) of all strings that are "like" s.
other opearions:
`set_X(s,c)` --- set X of String s as c.
`get_x(s)` --- return X value of s.
`insert (s,x)` --- create new data entry
`selete(s,x)` --- delete an existing entry
DataEntry structure (as u would have already guessed)
{
string s;
int x;
}

How can I sort a list of strings in Dart?

I see in the API docs there is a sort() method on List, but I'm not clear what it needs for a parameter. The current need is for a very simple straight up alpha comparison.
1. A Quick Solution
Thanks for the question! You can sort a list of Strings like this:
main() {
final List<String> fruits = <String>['bananas', 'apples', 'oranges'];
fruits.sort();
print(fruits);
}
The above code prints:
[apples, bananas, oranges]
2. Slightly more advanced usage
Notice that sort() does not return a value. It sorts the list without creating a new list. If you want to sort and print in the same line, you can use method cascades:
print(fruits..sort());
For more control, you can define your own comparison logic. Here is an example of sorting the fruits based on price.
main() {
final List<String> fruits = <String>['bananas', 'apples', 'oranges'];
fruits.sort((a, b) => getPrice(a).compareTo(getPrice(b)));
print(fruits);
}
Let's see what's going on here.
A List has a sort method, which has one optional parameter: a Comparator. A Comparator is a typedef or function alias. In this case, it's an alias for a function that looks like:
int Comparator(T a, T b)
From the docs:
A Comparator function represents such a total ordering by returning a negative integer if a is smaller than b, zero if a is equal to b, and a positive integer if a is greater than b.
3. How to do it with a list of custom objects
Additionally, if you create a list composed of custom objects, you could add the Comparable<T> as a mixin or as inheritance (extends) and then override the compareTo method, in order to recreate the standard behavior of sort() for your list of custom objects. For more info, do check out this other, related StackOverflow answer.
Here is the one line code to achieve it.
fruits.sort((String a, String b)=>a.compareTo(b)); //fruits is of type List<String>
For Sorting Simple List of Integers or Strings:
var list = [5 , -5 ,1];
list.sort(); //-5 , 1 , 5
For Reversing the list order:
list.reversed;
For Sorting List of Objects or Map by field of it:
List<Map<String, dynamic>> list= [
{"name": "Shoes", "price": 100},
{"name": "Pants", "price": 50},
];
// from low to high according to price
list.sort((a, b) => a["price"].compareTo(b["price"]));
// from high to low according to price
list.sort((a, b) => b["price"].compareTo(a["price"]));
To add just one point to Seth's detailed answer, in general, in
(a, b) => foo(a, b)
passed into sort, the function foo should answer an integer result as follows:
if a < b, result should be < 0,
if a = b, result should be = 0, and
if a > b, result should be > 0.
For the above law of trichotomy to hold, both a and b must be Comparables.
use compareAsciiUpperCase instead of compareTo, as it supports strings and automatically ignores case sensitive:
import "package:collection/collection.dart";
data.sort((a, b) {
return compareAsciiUpperCase(a.name, b.name);
});
After today, you should just be able to do list.sort() .
The sort method's argument is now optional, and it defaults to a function that calls compareTo on the elements themselves. Since String is Comparable, it should Just Work now.
How I have solved this problem.
List<Product> _dataSavingListProducts = [];
List<Product> _dataSavingListFavoritesProducts = [];
void _orderDataSavingLists() {
_dataSavingListProducts.toList().reversed;
_dataSavingListFavoritesProducts.toList().reversed;
}

Resources