Search Results

Search found 55517 results on 2221 pages for 'set intersection'.

Page 4/2221 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Problem in java.util.Set.addAll() method

    - by Yatendra Goel
    I have a java.util.Set<City> cities and I need to add cities to this set in 2 ways: By adding individual city (with the help of cities.add(city) method call) By adding another set of cities to this set (with the help of cities.addAll(anotherCitiesSet) method call) But the problem in second approach is that i don't know whether there were any duplicate cities in the anotherCitiesSet. I want to do some processing whenever a duplicate entry is tried to be entered in thecities set.

    Read the article

  • java: retrieving the "canonical value" from a Set<T> where T has a custom equals()

    - by Jason S
    I have a class Foo which overrides equals() and hashCode() properly. I would like to also would like to use a HashSet<Foo> to keep track of "canonical values" e.g. I have a class that I would like to write like this, so that if I have two separate objects that are equivalent I can coalesce them into references to the same object: class Canonicalizer<T> { final private Set<T> values = new HashSet<T>(); public T findCanonicalValue(T value) { T canonical = this.values.get(value); if (canonical == null) { // not in the set, so put it there for the future this.values.add(value); return value; } else { return canonical; } } } except that Set doesn't have a "get" method that would return the actual value stored in the set, just the "contains" method that returns true or false. (I guess that it assumes that if you have an object that is equal to a separate object in the set, you don't need to retrieve the one in the set) Is there a convenient way to do this? The only other thing I can think of is to use a map and a list: class Canonicalizer<T> { // warning: neglects concurrency issues final private Map<T, Integer> valueIndex = new HashMap<T, Integer>(); final private List<T> values = new ArrayList<T>(); public T findCanonicalValue(T value) { Integer i = this.valueIndex.get(value); if (i == null) { // not in the set, so put it there for the future i = this.values.size(); this.values.add(value); this.valueIndex.put(value, i); return value; } else { // in the set return this.values.get(i); } } }

    Read the article

  • Set Theory and .NET

    - by MasterMax1313
    Recently I came across a situation where set theory and set math fit what I was doing to the letter (granted there was an easier way to accomplish what I needed - i.e. LINQ - but I didn't think of that at the time). However I didn't know of any generic set libraries. Granted IEnumerables provide some set operations (Union, etc.), but nothing like Intersection or set comparison. Can anyone point out something that fits here? Something that implements set math using a generic type?

    Read the article

  • Is it faster to loop through a Python set of number or a set of letters?

    - by Scott Bartell
    Is it faster to loop through a Python set of numbers or a Python set of letters given that each set is the exact same length and each item within each set is the same length? Why? I would think that there would be a difference because letters have more possible characters [a-zA-Z] than numbers [0-9] and therefor would be more 'random' and likely affect the hashing to some extent. numbers = set([00000,00001,00002,00003,00004,00005, ... 99999]) letters = set(['aaaaa','aaaab','aaaac','aaaad', ... 'aaabZZ']) # this is just an example, it does not actually end here for item in numbers: do_something() for item in letters: do_something() where len(numbers) == len(letters) Update: I am interested in Python's specific hashing algorithm and what happens behind the scenes with this implementation.

    Read the article

  • Python: Access members of a set

    - by emu
    Say I have a set myset of custom objects that may be equal although their references are different (a == b and a is not b). Now if I add(a) to the set, Python correctly assumes that a in myset and b in myset even though there is only len(myset) == 1 object in the set. That is clear. But is it now possible to extract the value of a somehow out from the set, using b only? Suppose that the objects are mutable and I want to change them both, having forgotten the direct reference to a. Put differently, I am looking for the myset[b] operation, which would return exactly the member a of the set. It seems to me that the type set cannot do this (faster than iterating through all its members). If so, is there at least an effective work-around?

    Read the article

  • Python: Behavior of object in set operations

    - by Josh Arenberg
    I'm trying to create a custom object that behaves properly in set operations. I've generally got it working, but I want to make sure I fully understand the implications. In particular, I'm interested in the behavior when there is additional data in the object that is not included in the equal / hash methods. It seems that in the 'intersection' operation, it returns the set of objects that are being compared to, where the 'union' operations returns the set of objects that are being compared. To illustrate: class MyObject: def __init__(self,value,meta): self.value = value self.meta = meta def __eq__(self,other): if self.value == other.value: return True else: return False def __hash__(self): return hash(self.value) a = MyObject('1','left') b = MyObject('1','right') c = MyObject('2','left') d = MyObject('2','right') e = MyObject('3','left') print a == b # True print a == c # False for i in set([a,c,e]).intersection(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 right #2 right for i in set([a,c,e]).union(set([b,d])): print "%s %s" % (i.value,i.meta) #returns: #1 left #3 left #2 left Is this behavior documented somewhere and deterministic? If so, what is the governing principle?

    Read the article

  • Gvim displays wrong font when set from _gvimrc, but correct font when set from menus

    - by dggoldst
    This question applies to gVim running on Windows. I have the following line in my _gvimrc set guifont=Lucida_Sans_Typewriter:h11:cANSI When gVim starts up, it strange italicizes everything! A call to :set guifont shows that things seem to have been set correctly, as it returns guifont=Lucida_Sans_Typewriter:h11:cANSI Then I manually select Edit-Select Font ... and then choose Lucida Sans Typewriter, and font size 11 and submit, the italics disappear and it looks fine. I've posted my _gvimrc for reference at http://vim.pastey.net/132157 So my questions are: Why am I getting different results from setting it manually and from _gvimrc? Is there a way to capture the command that the dialog box is sending back to the program? It might include extra commands that I'm missing.

    Read the article

  • C - How to implement Set data structure?

    - by psihodelia
    Is there any tricky way to implement a set data structure (a collection of unique values) in C? All elements in a set will be of the same type and there is a huge RAM memory. As I know, for integers it can be done really fast'N'easy using value-indexed arrays. But I'd like to have a very general Set data type. And it would be nice if a set could include itself.

    Read the article

  • C++: set of C-strings

    - by Nicholas
    I want to create one so that I could check whether a certain word is in the set using set::find However, C-strings are pointers, so the set would compare them by the pointer values by default. To function correctly, it would have to dereference them and compare the strings. I could just pass the constructor a pointer to the strcmp() function as a comparator, but this is not exactly how I want it to work. The word I might want to check could be part of a longer string, and I don't want to create a new string due to performance concerns. If there weren't for the set, I would use strncmp(a1, a2, 3) to check the first 3 letters. In fact, 3 is probably the longest it could go, so I'm fine with having the third argument constant. Is there a way to construct a set that would compare its elements by calling strncmp()? Code samples would be greatly appreciated.

    Read the article

  • AS3: Adding get/set methods to a class via prototype

    - by LiraNuna
    I'm looking for a way to extend a class via prototype by adding a get and set functions. The following code will add a function to the class' prototype: MyClass.prototype.newMethod = function(... args) { }; However I want to add both a get and set functions. I tried: MyClass.prototype.fakeProperty = get function(... args) { }; MyClass.prototype.fakeProperty = set function(... args) { }; But that seem to throw compile errors. Is this even possible? Is there some 'internal' naming convention for get/set functions? I am not looking for answers such as 'create a new class and new get/set functions there'.

    Read the article

  • taking intersection of N-many lists in python

    - by user248237
    what's the easiest way to take the intersection of N-many lists in python? if I have two lists a and b, I know I can do: a = set(a) b = set(b) intersect = a.intersection(b) but I want to do something like a & b & c & d & ... for an arbitrary set of lists (ideally without converting to a set first, but if that's the easiest / most efficient way, I can deal with that.) I.e. I want to write a function intersect(*args) that will do it for arbitrarily many sets efficiently. What's the easiest way to do that? EDIT: My own solution is reduce(set.intersection, [a,b,c]) -- is that good? thanks.

    Read the article

  • SET game odds simulation (MATLAB)

    - by yuk
    Here is an interesting problem for your weekend. :) I recently find the great card came - SET. Briefly, there are 81 cards with the four features: symbol (oval, squiggle or diamond), color (red, purple or green), number (one, two or three) or shading (solid, striped or open). The task is to find (from selected 12 cards) a SET of 3 cards, in which each of the four features is either all the same on each card or all different on each card (no 2+1 combination). In my free time I've decided to code it in MATLAB to find a solution and to estimate odds of having a set in randomly selected cards. Here is the code: %% initialization K = 12; % cards to draw NF = 4; % number of features (usually 3 or 4) setallcards = unique(nchoosek(repmat(1:3,1,NF),NF),'rows'); % all cards: rows - cards, columns - features setallcomb = nchoosek(1:K,3); % index of all combinations of K cards by 3 %% test tic NIter=1e2; % number of test iterations setexists = 0; % test results holder % C = progress('init'); % if you have progress function from FileExchange for d = 1:NIter % C = progress(C,d/NIter); % cards for current test setdrawncardidx = randi(size(setallcards,1),K,1); setdrawncards = setallcards(setdrawncardidx,:); % find all sets in current test iteration for setcombidx = 1:size(setallcomb,1) setcomb = setdrawncards(setallcomb(setcombidx,:),:); if all(arrayfun(@(x) numel(unique(setcomb(:,x))), 1:NF)~=2) % test one combination setexists = setexists + 1; break % to find only the first set end end end fprintf('Set:NoSet = %g:%g = %g:1\n', setexists, NIter-setexists, setexists/(NIter-setexists)) toc 100-1000 iterations are fast, but be careful with more. One million iterations takes about 15 hours on my home computer. Anyway, with 12 cards and 4 features I've got around 13:1 of having a set. This is actually a problem. The instruction book said this number should be 33:1. And it was recently confirmed by Peter Norvig. He provides the Python code, but I didn't test it. So can you find an error?

    Read the article

  • Whats the best to way convert a set of Java objects to another set of objects?

    - by HDave
    Basic Java question here from a real newbie. I have a set of Java objects (of class "MyClass") that implement a certain interface (Interface "MyIfc"). I have a set of these objects stored in a private variable in my class that is declared as follows: protected Set<MyClass> stuff = new HashSet<MyClass>(); I need to provide a public method that returns this set as a collection of objects of type "MyIfc". public Collection<MyIfc> getMyStuff() {...} How do I do the conversion? The following line gives me an error that it can't do the conversion. I would have guessed the compiler knew that objects of class MyClass implemented MyIfc and therefore would have handled it. Collection<MyIfc> newstuff = stuff; Any enlightenment is appreciated.

    Read the article

  • Implementing set operations in TSQL

    - by dotneteer
    SQL excels at operating on dataset. In this post, I will discuss how to implement basic set operations in transact SQL (TSQL). The operations that I am going to discuss are union, intersection and complement (subtraction).   Union Intersection Complement (subtraction) Implementing set operations using union, intersect and except We can use TSQL keywords union, intersect and except to implement set operations. Since we are in an election year, I will use voter records of propositions as an example. We create the following table and insert 6 records into the table. declare @votes table (VoterId int, PropId int) insert into @votes values (1, 30) insert into @votes values (2, 30) insert into @votes values (3, 30) insert into @votes values (4, 30) insert into @votes values (4, 31) insert into @votes values (5, 31) Voters 1, 2, 3 and 4 voted for proposition 30 and voters 4 and 5 voted for proposition 31. The following TSQL statement implements union using the union keyword. The union returns voters who voted for either proposition 30 or 31. select VoterId from @votes where PropId = 30 union select VoterId from @votes where PropId = 31 The following TSQL statement implements intersection using the intersect keyword. The intersection will return voters who voted only for both proposition 30 and 31. select VoterId from @votes where PropId = 30 intersect select VoterId from @votes where PropId = 31 The following TSQL statement implements complement using the except keyword. The complement will return voters who voted for proposition 30 but not 31. select VoterId from @votes where PropId = 30 except select VoterId from @votes where PropId = 31 Implementing set operations using join An alternative way to implement set operation in TSQL is to use full outer join, inner join and left outer join. The following TSQL statement implements union using full outer join. select Coalesce(A.VoterId, B.VoterId) from (select VoterId from @votes where PropId = 30) A full outer join (select VoterId from @votes where PropId = 31) B on A.VoterId = B.VoterId The following TSQL statement implements intersection using inner join. select Coalesce(A.VoterId, B.VoterId) from (select VoterId from @votes where PropId = 30) A inner join (select VoterId from @votes where PropId = 31) B on A.VoterId = B.VoterId The following TSQL statement implements complement using left outer join. select Coalesce(A.VoterId, B.VoterId) from (select VoterId from @votes where PropId = 30) A left outer join (select VoterId from @votes where PropId = 31) B on A.VoterId = B.VoterId where B.VoterId is null Which one to choose? To choose which technique to use, just keep two things in mind: The union, intersect and except technique treats an entire record as a member. The join technique allows the member to be specified in the “on” clause. However, it is necessary to use Coalesce function to project sets on the two sides of the join into a single set.

    Read the article

  • Set Covering : Runtime hang\error at function call in c

    - by EnthuCrazy
    I am implementing a set covering application which uses cover function int cover(set *skill_list,set *player_list,set *covering) Suppose skill_set={a,b,c,d,e}, player_list={s1,s2,s3} then output coverin ={s1,s3} where say s1={a,b,c}, s3={d,e} and s2={b,d}. Now when I am calling this function it's hanging at run (set_cover.exe stopped working). Here is my cover function: typedef struct Spst_{ void *key; set *st; }Spst; int cover(set *skill_list,set *player_list,set *covering) { Liste *member,*max_member; Spst *subset; set *intersection; void **data; int max_size; set_init(covering); //to initialize set covering initially while(skill_list->size>0&&player_list->size>0) { max_size=0; for(member=player_list->head;member!=NULL;member=member->next) { if(set_intersection(intersection,((Spst *)(member->data))->st,skill_list)!=0) return -1; if(intersection->size>max_size) { max_member=member; max_size=intersection->size; } set_destroy(intersection); //at the end of iteration } if(max_size==0) //to check for no covering return -1; subset=(Spst *)max_member->data; //to insert max subset from play list to covering set set_inselem(covering,subset); for(member=(((Spst *)max_member->data)->st->head);member!=NULL;member=member->next) //to rem elem from skill list { data=(void **)member->data; set_remelem(skill_list,data); } set_remelem(player_list,(void **)subset); //to rem subset from set of subsets play list } if(skill_list->size>0) return -1; return 0; } Now assuming I have defined three set type sets(as stated above) and calling from main as cover(skills,subsets,covering);=> runtime hang Here Please give inputs on the missing link in this or the prerequisites for a proper call to this function type required. EDIT: Assume other functions used in cover are tested and working fine.

    Read the article

  • Data structure to build and lookup set of integer ranges

    - by actual
    I have a set of uint32 integers, there may be millions of items in the set. 50-70% of them are consecutive, but in input stream they appear in unpredictable order. I need to: Compress this set into ranges to achieve space efficient representation. Already implemented this using trivial algorithm, since ranges computed only once speed is not important here. After this transformation number of resulting ranges is typically within 5 000-10 000, many of them are single-item, of course. Test membership of some integer, information about specific range in the set is not required. This one must be very fast -- O(1). Was thinking about minimal perfect hash functions, but they do not play well with ranges. Bitsets are very space inefficient. Other structures, like binary trees, has complexity of O(log n), worst thing with them that implementation make many conditional jumps and processor can not predict them well giving poor performance. Is there any data structure or algorithm specialized in integer ranges to solve this task?

    Read the article

  • Pair equal operator overloading for inserting into set

    - by Petwoip
    I am trying to add a pair<int,int> to a set. If a pair shares the same two values as another in the set, it should not be inserted. Here's my non-working code: typedef std::pair<int, int> PairInt; template<> bool std::operator==(const PairInt& l, const PairInt& r) { return (l.first == r.first && l.second == r.second) || (l.first == r.second && l.second == r.first); } int main() { std::set<PairInt> intSet; intSet.insert(PairInt(1,3)); intSet.insert(PairInt(1,4)); intSet.insert(PairInt(1,4)); intSet.insert(PairInt(4,1)); } At the moment, the (4,1) pair gets added even though there is already a (1,4) pair. The final contents of the set are: (1 3) (1 4) (4 1) and I want it to be (1 3) (1 4) I've tried putting breakpoints in the overloaded method, but they never get reached. What have I done wrong?

    Read the article

  • Finding Z given X & Y coordinates on terrain?

    - by mrky
    I need to know what the most efficient way of finding Z given X & Y coordinates on terrain. My terrain is set up as a grid, each grid block consisting of two triangles, which may be flipped in any direction. I want to move game objects smoothly along the floor of the terrain without "stepping." I'm currently using the following method with unexpected results: double mapClass::getZ(double x, double y) { int vertexIndex = ((floor(y))*width*2)+((floor(x))*2); vec3ray ray = {glm::vec3(x, y, 2), glm::vec3(x, y, 0)}; vec3triangle tri1 = { glmFrom(vertices[vertexIndex].v1), glmFrom(vertices[vertexIndex].v2), glmFrom(vertices[vertexIndex].v3) }; vec3triangle tri2 = { glmFrom(vertices[vertexIndex+1].v1), glmFrom(vertices[vertexIndex+1].v2), glmFrom(vertices[vertexIndex+1].v3) }; glm::vec3 intersect; if (!intersectRayTriangle(tri1, ray, intersect)) { intersectRayTriangle(tri2, ray, intersect); } return intersect.z; } intersectRayTriangle() and glmFrom() are as follows: bool intersectRayTriangle(vec3triangle tri, vec3ray ray, glm::vec3 &worldIntersect) { glm::vec3 barycentricIntersect; if (glm::intersectLineTriangle(ray.origin, ray.direction, tri.p0, tri.p1, tri.p2, barycentricIntersect)) { // Convert barycentric to world coordinates double u, v, w; u = barycentricIntersect.x; v = barycentricIntersect.y; w = 1 - (u+v); worldIntersect.x = (u * tri.p0.x + v * tri.p1.x + w * tri.p2.x); worldIntersect.y = (u * tri.p0.y + v * tri.p1.y + w * tri.p2.y); worldIntersect.z = (u * tri.p0.z + v * tri.p1.z + w * tri.p2.z); return true; } else { return false; } } glm::vec3 glmFrom(s_point3f point) { return glm::vec3(point.x, point.y, point.z); } My convenience structures are defined as: struct s_point3f { GLfloat x, y, z; }; struct s_triangle3f { s_point3f v1, v2, v3; }; struct vec3ray { glm::vec3 origin, direction; }; struct vec3triangle { glm::vec3 p0, p1, p2; }; vertices is defined as: std::vector<s_triangle3f> vertices; Basically, I'm trying to get the intersect of a ray (which is positioned at the x, and y coordinates specified facing pointing downwards toward the terrain) and one of the two triangles on the grid. getZ() rarely returns anything but 0. Other times, the numbers it generates seem to be completely off. Am I taking the wrong approach? Can anyone see a problem with my code? Any help or critique is appreciated!

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >