I want to create linked lists of objects sorted by an object attribute (physical size); but so far it seems I will have to code them myself...
These lists will be short, typically a dozen nodes each; but I may have up to a thousand lists; so I can't afford the extra weight of using std::map's. In fact, I'd be quite happy with single linked list.
But I need the node to be more than just a value.
The key value in my objects is rarely going to change; however elements will have to come out of one list and move to another quite often.
((Actual use: One list per quad, in a quad-tree (as for collision detection, etc); objects sorted by size, as the larger objects are less numerous but need to be picked quickly from larger ranges, so they should come up first in the lists.))
But every example I find for using std::list to maintain sorted lists uses a list of integers as the example; but that's not very useful; what I have is objects that have one value member to be sorted by.
I was thinking of using lower_bound to find the insertion point, then insert the object; but the lower_bound iterator takes a begin, and end, and a plain value as the third argument; I see no mechanism by which I can specify to use a particular member of my objects to sort by.
I could, of course, define a conversion operator,
my_object_type::int(){ return sortby; }
Would that work? Is there a better way?
I seem to have found my answer in this reference:
https://www.geeksforgeeks.org/lower_bound-in-cpp/
under "Syntax 2"; there is provision for a fourth
argument being a comparison functor. So, something
like this should work (not tested yet):
class pnt_proxy
{
int x; //position
int y;
point* real_pnt; //the real point this represents
public:
float sz; //rough largest diagonal across object
}
class pproxy_cmp : public std::binary_function< pnt_proxy, pnt_proxy, bool >
{
public:
bool operator()( pnt_proxy const & a, pnt_proxy const & b ) const
{
return a.sz < b.sz;
}
};
std::list< pnt_proxy > ll;
void insert_sorted( pnt_proxy const & pp )
{
if( ll.size() )
{
std::list<pnt_proxy>::iterator insert_at;
insert_at =
std::lower_bound( ll.begin(), ll.end(), pp, pproxy_cmp() );
ll.insert( insert_at, pp );
}
else ll.push_back( pp );
}
Related
I trying to write a random parameter to my program, but my program some parameter will use other parameter for range. I try to get from online but cannot get it. Then, i decide come here ask about it.
Hope anyone can help.
rand bit COMMON_CLK;
rand int DEPTH;
rand int DATA_WIDTH
rand int PROG_FULL_ASSERT;
rand int PROG_FULL_NEGATE;
rand int PROG_EMPTY_ASSERT;
rand int PROG_EMPTY_NEGATE;
constraint DEPTH {
DEPTH inside {[16:100000]};
DATA_WIDTH inside {[1:1024]};
}
constraint ASSERT {
PROG_FULL_ASSERT inside {[1:DEPTH.size]};
}
constraint NEGATE {
PROG_FULL_NEGAT inside {(1:PROG_FULL_ASSERT.size]};
}
constraint ASSERT {
PROG_EMPTY_ASSERT inside {[1:((DEPTH.size) - 1)]};
}
constraint NEGATE {
PROG_EMPTY_NEGATE inside {[(PROG_EMPTY_ASSERT.size) : ((DEPTH.size) - 1)]};
}
First, like Dave_59 pointed out DEPTH.size is not good code even if it does do something legal.
Secondly, if you wanted something like PROG_FULL_ASSERT inside {[1:DEPTH]}; you may want to add solve DEPTH before PROG_FULL_ASSERT to avoid distribution issues.
Lastly, in my experience sometimes it's better or at least easier to randomize some things in post.randomize(). This is assuming that nothing else is depending on them. For example:
int array;
rand int array_size;
constraint {array_size inside [100000:200000];}
void function post_randomize();
array = new[array_size];
array_data_randomization_function();
endfunction
This is not always a good idea because it adds the risk of later adding rand variables that depend on the post randomized one (array), BUT it does break the randomization to two independent actions, making the code easier to understand, and in case of heavy randomizations also makes it calculate faster.
I'm fiddling around with GlobalObjectKey, where my objects are DateTime instances. I noticed that if I create new instances of the same date and time, I get the same instance "ID":
DateTime newInstance = new DateTime.fromMicrosecondsSinceEpoch(datetime.microsecondsSinceEpoch);
My debug prints say that there are two separate keys with the same id:
[GlobalObjectKey DateTime#f056e] // Key assigned to Widget1
[GlobalObjectKey DateTime#f056e] // Key assigned to Widget2
However, even though the keys seem to be duplicates, I don't seem to get any widget/build errors.
Here's a more complete example of what I'm doing:
class DateTimeKey{
GlobalObjectKey key;
DateTimeKey(DateTime datetime){
DateTime newInstance = new DateTime.fromMicrosecondsSinceEpoch(datetime.microsecondsSinceEpoch);
key = new GlobalObjectKey(newInstance);
}
}
...
List<DateTimeKey> _bookingListMonthKeys = [];
List<DateTimeKey> _bookingListDayKeys = [];
DateTimeKey _monthKey = new DateTimeKey(theDate);
_bookingListMonthKeys.add(_monthKey);
DateTimeKey _dayKey = new DateTimeKey(theDate); // theDate here refers to the same DateTime instance as above
_bookingListDayKeys.add(_dayKey);
Even if I loop through both lists and cross reference them like this
_bookingListDayKeys.forEach((dayKey){
_bookingListMonthKeys.forEach((monthKey){
if( identical(dayKey, monthKey) )
print('Identical DateTimeKeys found: $dayKey, $monthKey');
if( identical(dayKey.key, monthKey.key) )
print('Identical GlobalObjectKeys found: ${dayKey.key}, ${monthKey.key}');
});
});
it doesn't show any duplicates, yet the printouts above clearly have the same "id" (#f056e). Can someone explain what's going on here?
So I think I figured out what's going on here.
First, the hash number in the question comes from the hashCode property of the DateTime instance. This is used for comparisons by the == operator, and hence will be the same for two DateTime instances that represent the same moment in time.
Sidenote: The actual string being printed (#f056e) seems to be the last 5 characters of the hexadecimal representation of the hashCode, which is an int.
However, hashCode is not used by GlobalObjectKey. Instead, it uses the method identityhashCode() from dart:core:
Returns the identity hash code of object.
Returns the same value as object.hashCode if object has not overridden Object.hashCode. > Returns the value that Object.hashCode would return on this object, even if hashCode has > been overridden.
This hash code is compatible with identical.
When creating two different DateTime instances from the same moment in time, their hashCode properties will be equal but the result of identityHashCode() will be different. So basically it seems like identityHashCode() is the closest substitute for an actual "memory address" of an object we will get.
DateTime instance1 = DateTime.now();
DateTime instance2 = DateTime.fromMicrosecondsSinceEpoch(instance1.microsecondsSinceEpoch);
print('hashCode: ${instance1.hashCode}, ${instance2.hashCode} identityHashCode: ${identityHashCode(instance1)}, ${identityHashCode(instance2)}');
will result in:
I/flutter (23321): hashCode: 89064814, 89064814 identityHashCode: 383428552, 594747591
Now it's clear to see that the hashCode is equal for both instances, but identityHashCode(DateTime) is different, meaning that they are in fact separate instances but equal when comparing their hashCode property or doing a == operation.
Why printing a GlobalObjectKey would print the hashCode of its value is still beyond me though, that's what threw me off from the start.
I am looking for examples of Chapel passing by reference. This example works but it seems like bad form since I am "returning" the input. Does this waste memory? Is there an explicit way to operate on a class?
class PowerPuffGirl {
var secretIngredients: [1..0] string;
}
var bubbles = new PowerPuffGirl();
bubbles.secretIngredients.push_back("sugar");
bubbles.secretIngredients.push_back("spice");
bubbles.secretIngredients.push_back("everything nice");
writeln(bubbles.secretIngredients);
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
bubbles = kickAss(bubbles);
writeln(bubbles.secretIngredients);
And it produces the output
sugar spice everything nice
sugar spice everything nice Chemical X
What is the most efficient way to use a function to modify Bubbles?
Whether Chapel passes an argument by reference or not can be controlled by the argument intent. For example, integers normally pass by value but we can pass one by reference:
proc increment(ref x:int) { // 'ref' here is an argument intent
x += 1;
}
var x:int = 5;
increment(x);
writeln(x); // outputs 6
The way that a type passes when you don't specify an argument is known as the default intent. Chapel passes records, domains, and arrays by reference by default; but of these only arrays are modifiable inside the function. ( Records and domains pass by const ref - meaning they are passed by reference but that the function they are passed to cannot modify them. Arrays pass by ref or const ref depending upon what the function does with them - see array default intent ).
Now, to your question specifically, class instances pass by "value" by default, but Chapel considers the "value" of a class instance to be a pointer. That means that instead of allowing a field (say) to be mutated, passing a class instance by ref just means that it could be replaced with a different class instance. There isn't currently a way to say that a class instance's fields should not be modifiable in the function (other than making them to be explicitly immutable data types).
Given all of that, I don't see any inefficiencies with the code sample you provided in the question. In particular, here:
proc kickAss(b: PowerPuffGirl) {
b.secretIngredients.push_back("Chemical X");
return b;
}
the argument accepting b will receive a copy of the pointer to the instance and the return b will return a copy of that pointer. The contents of the instance (in particular the secretIngredients array) will remain stored where it was and won't be copied in the process.
One more thing:
This example works but it seems like bad form since I am "returning" the input.
As I said, this isn't really a problem for class instances or integers. What about an array?
proc identity(A) {
return A;
}
var A:[1..100] int;
writeln(identity(A));
In this example, the return A in identity() actually does cause a copy of the array to be made. That copy wasn't created when passing the array in to identity(), since the array was passed by with a const ref intent. But, since the function returns something "by value" that was a reference, it's necessary to copy it as part of returning. See also arrays return by value by default in the language evolution document.
In any case, if one wants to return an array by reference, it's possible to do so with the ref or const ref return intent, e.g.:
proc refIdentity(ref arg) ref {
return arg;
}
var B:[1..10] int;
writeln(refIdentity(B));
Now there is no copy of the array and everything is just referring to the same B.
Note though that it's currently possible to write programs that return a reference to a variable that no longer exists. The compiler includes some checking in that area but it's not complete. Hopefully improvements in that area are coming soon.
// Current Class
class x;
rand int a;
int b; // b is nonrandom as of now
function new();
endfunction
function abc;
// if a != ref.a, where ref is reference object of class x, declared somewhere else
a.rand_mode(0);
endfunciton
// Future Possible Class
class x;
rand int a;
rand int b; // b is also a random variable now
function new();
endfunction
function abc;
// if a != ref.a, where ref is reference object of class x, declared somewhere else
a.rand_mode(0);
// if b != ref.b, where ref is reference object of class x, declared somewhere else
b.rand_mode(0);
endfunciton
So in function abc, depending upon whether a rand member value matches or doesn't match with the value of that member in reference class, that rand declared members of class x, should be active or inactive accordinly.
Purpose - I need to check if a rand variable matches with reference class value then only it should be randomized, otherwise not.
I want to generalize method abc, for all possible future variations (So I don't need to modify it, as done in the above example), and as I don't know, when a class member may become rand or nonrand member, Is there any inbuilt method to know, whether a member of a class is declared as rand or not in that class?
You could change your perspective on the problem slightly. Instead of trying to disable randomization for fields that are declared rand, why not say that when they get randomized, they should keep their value?
According to this nice post, there's a new construct in SV 2012, const'(...) that would work in this case. Unfortunately I don't think many vendors support it. Your randomize() call would look like this:
if (!rand_obj.randomize() with {
const'(a) != ref_obj.a -> a == const'(a);
})
$fatal(0, "rand error");
Let's dissect this code. const(a) will sample the value of a prior to doing any sort of randomization. If the value of a before randomization is not equal to the reference value, then we have the second part of the constraint that says a should keep its value. I've tried this code on two simulators but it wasn't supported by either (though it should be legal SV 2012 syntax). Maybe you're lucky enough to have a vendor that supports it.
You can write such constraints even for state variables, as they will still hold.
If you can't get the const syntax to work in your simulator, then the same post shows how you could work around the issue. You could store the values prior to randomization inside the object and use those in the constraint:
class some_class;
rand bit [2:0] a;
bit [2:0] b;
bit [2:0] pre_rand_a;
bit [2:0] pre_rand_b;
function void pre_randomize();
pre_rand_a = a;
pre_rand_b = b;
endfunction
endclass
When you want to randomize, you'd add the following constraints:
if (!rand_obj.randomize() with {
pre_rand_a != ref_obj.a -> a == pre_rand_a;
pre_rand_b != ref_obj.b -> b == pre_rand_b;
})
$fatal(0, "rand error");
You can find a full example on EDAPlayground.
You mention that your function that does randomization is defined outside of the object. Because of that, the pre_rand_* fields can't be local/protected, which isn't very nice. You should consider making the function a class member and pass the reference object to it, so that you can enforce proper encapsulation.
This isn't possible as SystemVerilog doesn't provide any reflection capabilities. You could probably figure this out using the VPI, but I'm not sure how complete the implementation of the VPI is for classes.
Based on what you want to do, I'd say it anyway doesn't make sense to implement such a query just to future proof your code in case some fields will one day become rand. Just as how you add the rand modifier to the field, you can also add it to the list of fields for which randomization should be disabled. Both code locations reside in the same file, so it's difficult to miss.
One certain simulator will return -1 when interrogating a state variable's rand_mode(), but this is non-standard. The LRM explicitly states that it's a compile error to call rand_mode() on non-random fields.
I'm trying to get my head around using CoffeeScript comprehensions as efficiently as possible. I think I have basic mapping down -- turning one list into another -- but searching still seems verbose to me.
Say I have a map of items to shops:
shopMap:
toyStore: ["games", "puzzles"]
bookStore: ["novels", "picture books"]
and, given an item, I want to find out which shop it's in. What's the best way of doing that in CoffeeScript?
Here's how I could do in in JavaScript:
var shop = findShop(item);
function findShop(item) {
for (shop in shopMap)
itemList = shopMap[shop]
for (i = 0, ii = itemList.length; i<ii; i++) {
if (itemList[i] === item) {
return shop;
}
}
}
}
I used a function to allow it to quickly break out of the loops with the return statement, instead of using breaks, but the function is kind of fugly as this is only being used once.
So is there a shorter CS equivalent preferably one that doesn't require creating a new function?
You can try this:
findShop = (item) ->
for shop, items of shopMap
return shop if item in items
If you really want to try with a list comprehension, this is equivalent:
findShop = (item) ->
(shop for shop, items of shopMap when item in items)[0]
But i think the first one reads better (and also doesn't need to generate an intermediate array for the results). This would be a better approach IMO if you wanted to find all shops for a given item:
findShops = (item) ->
shop for shop, items of shopMap when item in items
If this is a common operation, you might be better off creating an intermediate data structure up front and doing the lookup directly.
shopMap =
toyStore: ["games", "puzzles"]
bookStore: ["novels", "picture books"]
categoryMap = {}
for k, v of shopMap
for category in v
categoryMap[category] = k
alert(categoryMap['puzzles'])
Demo
With this implementation you need to loop through the structure only once up front (plus possibly update it if shopMap changes). With yours and epidemian's answer, you have to loop every time you need to do this particular type of lookup. If you do this operation a lot, it could make a difference. On the other hand, if your shopMap is really large (like thousands of entries), then my implementation will take up more memory.
Depending upon how robust you want to make this, you might want to turn it into a Class and have any operations on it occur through the Class' interface. You'd need addCategory and deleteCategory methods as well as a getStoreFromCategory method, which is essentially what we are implementing above. This object-oriented approach would hide the internal data-structure/implementation so you could later alter the implementation to optimize for memory or speed.