Priority Queue object comparator with hashset object - priority-queue

HashSet Object ct_set City Object
how can i initialize a ProrityQueue object ct_pq with elements in ct_set with order from my populatation comparator

Create the PriorityQueue with your Comparator, and then just call addAll:
HashSet<City> cities = ...;
PriorityQueue<City> queue = new PriorityQueue(new CityComparator());
queue.addAll(cities);
Note that if you've really got a HashSet<Object> instead (your question is far from clear) you should probably try to change your code so that you do have a HashSet<City> instead. Or you can always just cast each element:
HashSet<Object> cities = ...;
PriorityQueue<City> queue = new PriorityQueue(new CityComparator());
for (Object x : cities) {
queue.add((City) x);
}

Related

Swift 3 references

When creating an instance of an object, I'm having trouble setting its properties if I assign the property to another variable.
Eg. For an object containing nested objects, I want to assign one of the children to a temporary var to make it easier to work with.
Instead of doing this (which works):
myObj.myChildObject[0].someOtherChild[0].property = "something"
I'm trying to do:
var t = myObj.myChildObject[0].someOtherChild[0]
t.property = "something"
// this doesn't throw an error but doesn't change the value of myObj
What gives?
Edit>
Here's a contrived example to illustrate:
class Car { var name: String = "" }
var merc = Car()
var obj = merc.name
merc.name = "C63 AMG"
obj = "E300"
print("merc.name: \(merc.name)") // prints merc.name: C63 AMG
print("obj.name: \(obj)") // prints obj.name: E300
var ob2 = merc
ob2.name = "Toyota"
print("ob2.name: \(ob2.name)") // prints ob2.name: Toyota
print("merc.name: \(merc.name)") // prints merc.name: Toyota
So assigning the class instance to a var creates a reference. But assigning a property of that object to another var creates a copy?
I read through https://developer.apple.com/swift/blog/?id=10 and still don't get it :(
In the above, 'obj' is not a struct, enum or tuple, so shouldn't it be a reference type?
If myObj.myChildObject[0].someOtherChild[0] is a value type (I.e. a strict, direct enum or tuple), it's being copied upon assignment to t. Subsequent mutations on t only mutate that copy, and the original instance are unchanged.
You would have to reassign t back in:
var t = myObj.myChildObject[0].someOtherChild[0]
t.property = "something"
myObj.myChildObject[0].someOtherChild[0] = t
This is discussed in the Swift language guide.

Threadsafe mutable collection with fast elements removal and random get

I need a thread safe data structure with three operations: remove, getRandom, reset.
I have only two ideas by now.
First: Seq in syncronized var.
val all: Array[String] = ... //all possible.
var current: Array[String] = Array.empty[String]
def getRandom(): = {
val currentAvailable = current
currentAvailable(Random.nextInt(currentAvailable.length))
}
def remove(s: String) = {
this.syncronized {
current = current diff Seq(s)
}
}
def reset(s: String) = {
this.syncronized {
current = all
}
}
Second:
Maintain some Map[String,Boolean], there bool is true when element currently is present. The main problem is to make a fast getRandom method (not something like O(n) in worst case).
Is there a better way(s) to implement this?
Scala's Trie is a lock free data structure that supports snapshots (aka your currentAvailable) and fast removals
Since I'm not a Scala expert so this answer is general as an example I used Java coding.
in short the answer is YES.
if you use a map such as :
Map<Integer,String> map=new HashMap<Integer,String>(); //is used to get random in constant time
Map<String,Integer> map1=new HashMap<String,Integer>(); //is used to remove in constant time
to store date,
the main idea is to keep the key( in this case the integer) synchronized to be {1 ... size of map}
for example to fill this structure, you need something like this:
int counter=0; //this is a global variable
for(/* all your string (s) in all */ ){
map.put(counter++, s);
}
//then , if you want the removal to be in constant time you need to fill the second map
for(Entry e : map.EntrySet(){
map1.put(e.getValue(),e.getKey());
}
The above code is the initialization. everytime you want to set things you need to do that
then you can achieve a random value with O(1) complexity
String getRandom(){
int i; /*random number between 0 to counter*/
return map.get(i);
}
Now to remove things you use map1 to achive it in constant time O(1);
void remove(String s){
if(!map1.containsKey(s))
return; //s doesn't exists
String val=map.get(counter); //value of the last
map.remove(counter) //removing the last element
int thisCounter= map1.get(s); //pointer to this
map1.remove(s); // remove from map1
map.remove(counter); //remove from map
map1.put(thisCounter,val); //the val of the last element with the current pointer
counter--; //reducing the counter by one
}
obviously the main issue here is to keep the synchronization ensured. but by carefully analyzing the code you should be able to do that.

Given a collection object, would like to assign to a local variable of specific type

I'd like to recover type information using reflection. I have
public Foo(object coll, string tValue)
{
var x = col1 as IList;
if (x != null)
x.Action();
var y = col1 as IDictionary;
if (y != null)
y.Action();
}
But would like to have
public Foo(object coll, string tValue)
{
var x = col1 as IList<TValue>;
if (x != null)
x.Action();
var y = col1 as IDictionary<int, TValue>;
if (y != null)
y.Action();
}
Is it possible to arrive at and use generic interfaces instead of the old-school non-generic collection interfaces, given only the contained class name?
Once the local variable type is established, I'd like to avoid paying the reflection and dynamic invocation penalties when looping over the collection.
Another example, maybe clearer:
var list = new Dictionary<int, MyObject>();
list.Add(100, new MyObject());
object listObject = list;
var x = listObject as IDictionary<int, dynamic>;
if (x != null)
{
foreach (var entry in x)
{
Console.WriteLine(entry.Key);
Console.WriteLine(entry.Value);
}
}
x is null...
I'm not sure if you intend to call a method on generic collection for every item in the collection or if you just want the values from the generic collection.
For your third block of code, you could continue to use the non-generic interface and use an enumerator.
var x = listObject as IDictionary;
if (x != null)
{
var en = x.GetEnumerator();
while(en.MoveNext())
{
Console.WriteLine(en.Key);
Console.WriteLine(en.Value);
}
}
If you intend to call a method without knowing the exact generic types for the generic IList or IDictionary, then you'll have to use MethodInfo.Invoke. Cache the MethodInfo outside of the loop for a small performance boost.
CreateDelegate would be faster, but you'll need to know the exact generic types. You could get around that with expression trees, but the amount of code to maintain might not be worth the performance gain. Check out MagicMethod in Jon Skeets article
Making reflection fly and exploring delegates

Java ME ArrayList - Vector - Define object types and access object methods through vector

I'm making a shopping list mobile application (Java ME) and i have two classes; item, list.
item object allows get/set name and quantity (string itemName, int quantity)
Now i need to store an array of items in my list class and be able to access the methods of the object from its list array index as follows; code below is pseudo code
item[] itemList = new item[]
for(int x = 0; x < itemList.length; x++)
{
String tempStoreOfName = itemList[x].getItemName()
System.out.println(tempStoreOfName)
}
I've googled a lot and found out that you can use vectors however i cannot seem to be able to call the object's methods. Where am i going wrong?
I've done something like this in C# and i used ArrayLists however these are not supported in Java ME
Current Code
Vector itemList = new Vector();
for(int x = 0; x <= itemList.size(); x++)
{
dataOutputStream.writeUTF(itemList.elementAt(x)*here i cannot put .getItemName()*);
}
Since you can't use generics you have to cast so that Java knows what you got out of the Vector. Notice that Vector.elementAt() returns Object? all you can do with it is treat it like an Object:
item myItem = itemList.elementAt(n);
fails because java can't auto-cast to a more specific class. You'd have to use:
Object myItem = itemList.elementAt(n);
which is useless to you because you want an item, not an Object.
You have to cast it to an object of the type you want:
for(...)
{
item myItem = (item) itemList.elementAt(n);
myItem.method();
}
From then on you just use myItem.

Problem with QVariant/QTreeWidgetItem/iterator on qt4.4.3

In my qt app I have this object, filled before setting up my QTreeWidget's content:
QList<QTreeWidgetItem*> items;
I fill the QList by this way:
QVariant qv; // I need this for "attaching" to the item my linuxPackage object
qv.setValue(linuxPackage);
packRow->setData(1, Qt::UserRole,qv); // packRow is my own object inherited from QTreeWidgetItem, I "put" the QVariant into it
items.append(packRow); // then I put my item into the QList
at the end of the work, my QList has almost 1000 items.
I need to iterate over them and for each item I need to get the "linuxPackage" data by this (tested and working) way:
Pkg linuxPackage = this->data(1,Qt::UserRole).value<Pkg>(); // Pkg is my own class for the linuxPackage object
So, I've been trying to extract needed data by this manner:
QList<QTreeWidgetItem*>::iterator iter;
for (iter = items.begin(); iter != items.end(); ++iter){
Pkg pack = iter->data(1,Qt::UserRole).value<Pkg>();
}
But nothing works, I can not even get the program compiling. Help! :D
Perhaps:
(*iter)->data(1,Qt::UserRole).value<Pkg>();
BTW, an easier way of doing this with Qt4:
foreach (const QTreeWidgetItem *item, items) {
Pkg pack = item->data(1,Qt::UserRole).value<Pkg>();
}
at the very least, you should use const_iterators =)
QList<QTreeWidgetItem*>::const_iterator iter;
for (iter = items.constBegin(); iter != items.constEnd(); ++iter){
...
}

Resources