PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label set. Show all posts
Showing posts with label set. Show all posts

Monday, November 7, 2022

[FIXED] How do I fill a Set with array of different object that extends the object in the Set

 November 07, 2022     arrays, casting, java, object, set     No comments   

Issue

How can I fill a Set<SomeObject>with array (Object[]) of different object that extends the object in the Set.

I got this array of objects which I want to cast into a Set of objects that extends the objects in the array Like this:

Object[] a = new Object[1];
a[0] = new SomeObject();
Set<SomeObject> aSet = new HashSet<SomeObject>(a);

If it is impossible to cast an array to a Set like that, is it then possible to cast an array to a List?

NOTE: If you want to achieve this the loop way like this:

Object[] a = new Object[1];
a[0] = new SomeObject("Something");
Set<SomeObject> aSet = new HashSet<SomeObject>();

for(int i = 0; i < a.length; i++){
    aSet.add((SomeObject)a[i])  
}

But I don't want to do it the loop way, and, yes, I know all objects extends the java.lang.Object class.


Solution

In response to OP's recent comment:

Somehow I can't cast this List to a Set so I let the method cast the List to a Array and return that Array

In that case you can simply do this:

List<SomeObject> list = ...
Set<SomeObject> set = new HashSet<SomeObject>(list);

What is important: This code has absolutely nothing to do with casting! What actually happens is that you have a List of objects and you create a new Set and copy all the elements from the list into it. The original list isn't modified by this operation.

To repeat my comment, you obviously have misunderstood what casting in Java means. Casting of object works in a very different way that casting of primitive values. Please read some article on this subject, such as this one: http://www.volantec.biz/castingObjects.htm



Answered By - Natix
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to check that only 1 element in a set has changed in a dafny ensures?

 November 07, 2022     dafny, set     No comments   

Issue

How can I check that only 1 element in a set has changed in a dafny ensures?

Example:

method myMethod(myParameter: int)
  requires myParameter >= 0
  modifies mySet
  ensures ONLY_ONE_ELEMENT_IN_THE_SET_HAS_CHANGED
{
  ...
}

Solution

If you mean that one element was removed and another was added, you need to provide them explicitly as (ghost) return variables and use the old keyword to reference the previous value of mySet

method myMethod(myParameter: int) returns (ghost removed: int, ghost added: int)
  requires myParameter >= 0
  modifies mySet
  ensures old(mySet) - {removed} + {added} == mySet
{
  ...
}


Answered By - Mikaël Mayer
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is time complexity of a list to set conversion?

 November 07, 2022     hash, list, python, set, time-complexity     No comments   

Issue

I've noticed the table of the time complexity of set operations on the python official website. But i just wanna ask what's the time complexity of converting a list to a set, for instance,

l = [1, 2, 3, 4, 5]
s = set(l)

I kind of know that this is actually a hash table, but how exactly does it work? Is it O(n) then?


Solution

Yes. Iterating over a list is O(n) and adding each element to the hash set is O(1), so the total operation is O(n).



Answered By - Mad Physicist
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] why duplicates removal in list using a set method gives output with different index each time?

 November 07, 2022     list, python, set     No comments   

Issue

I know to remove duplicates in a list...just curious to know why set does not give order as orginal list

my_list = ['apple', 'mango', 'grape', 'apple', 'guava', 'pumpkin']
>>>[*set(my_list)]

#output:
>>> ['mango', 'apple', 'grape', 'guava', 'pumpkin']
>>> ['pumpkin', 'guava', 'grape', 'mango', 'apple']

Solution

As all the comments say, a set is unordered, always.

But internally it uses a hash table, and IIRC the values stored are the hash of the object modulo the table size. Now small integers tend to have themselves as their hash values, so you may have the impression that they are sorted (not ordered by insertion order), but this won't always be the case:

ls = [1,2,3]
[*set(ls)]
[1, 2, 3]

ls = [2,1,3]
[*set(ls)]
[1, 2, 3]

ls2=[-1,-2,3]
[*set(ls2)]
[3, -1, -2]

ls2=[-2,-1,3]
[*set(ls2)]
[3, -2, -1]

Other objects, like the strings in your example, have very different hash values, so the behaviour is totally different:

hash('mango')
-7062263298897675226


Answered By - gimix
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to define comparator on SortedSet<> like TreeSet<>?

 November 07, 2022     collections, java, set     No comments   

Issue

I want to make a lexical sorted list of strings, so i went with the basic SortedSet

1)  Set<String> words = new SortedSet<String>(){}

and realized that SortedSet is an abstract class, in which I will have to implement the comapartor method. So i went and searched on google and found out that treeSet is better and i can use its predefined comparator method.

2)  SortedSet<String> words = new TreeSet<String>(){}

When went to java docs i realized that TreeSet extends AbstractSet rather than SortedSet. Question 1 - Can anyone explain how the 2nd line is still working(like i am not generalizing the Set which i would normally do instead i am using two totally different Classes with no Parent child relation). Question 2 - how to define comparator of SortedSet which will work as TreeSet. So here is the working code with TreeSet

SortedSet<String> words = new TreeSet<>();
    Scanner scanner1 = new Scanner(System.in);
    String s1 = scanner1.nextLine();
    int a = scanner1.nextInt();
    while(s1.length()>a){
        words.add(s1.substring(0,a));
        s1 = s1.substring(a);
    }
    Iterator itr  = words.iterator();
    while(itr!= null&&itr.hasNext()){
        System.out.println(itr.next());
    }

Normal Input

welcometojava
3

Expected Output

com
eto
jav
wel

Edit-1 For the answer of Question 2, i am expecting something like this

Set<String> words = new SortedSet<String>() {
        @Override
        public Comparator<? super String> comparator() {
            return null;
        }
        ......

I basically want to learn, how to make a basic comparator "like" in TreeSet while using SortedSet? I understand that if there is natural ordering i don't need to define a new comparator.


Solution

Answer 1:

TreeSet<T> implements the NavigableSet<T> interface, which extends SortedSet<T> who also extends Set<T>.

The interfaces themselves doesn't actually do the sorting, the concrete class does.

So:

Set<String> myStrings = new TreeSet<>();
// Add a bunch of strings
// ...
for (String s : myStrings) {
 System.out.println(s);
}

You would still have them in sorted order.

Answer 2:

Firstly, for classes that already implement Comparable<T>, you can omit the Comparator for the TreeSet, as "Natural Ordering" is meant by using the Comparable<T>'s compareTo method.

Otherwise you can supply a Comparator instance to as the TreeSet constructor's first argument:

    Set<String> myStrings = new TreeSet<>(new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            // Define comparing logic here
            return o1.compareTo(o2);
        }
    });

or use Java 8 Lambdas:

    Set<String> myStrings = new TreeSet<>((o1, o2) -> o1.compareTo(o2));


Answered By - kazenorin
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to print unique words from an inputted string

 November 07, 2022     python, python-3.5, set, string     No comments   

Issue

I have some code that I intend to print out all the unique words in a string that will be inputted by a user:

str1 = input("Please enter a sentence: ")

print("The words in that sentence are: ", str1.split())

unique = set(str1)
print("Here are the unique words in that sentence: ",unique)

I can get it to print out the unique letters, but not the unique words.


Solution

String.split(' ') takes a string and creates a list of elements divided by a space (' ').

set(foo) takes a collection foo and returns a set collection of only the distinct elements in foo.

What you want is this: unique_words = set(str1.split(' '))

The default value for the split separator is whitespace. I wanted to show that you can supply your own value to this method.



Answered By - Jordan McQueen
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How Set.contains() decides whether it's a subset or not?

 November 07, 2022     hashset, iterator, java, set, subset     No comments   

Issue

I expect the following code would give me a subset and a complementary set.

But actually, the result shows that "Error: This is not a subset!"

What it.next() get and how to revise my code to get the result I want? Thanks!

package Chapter8;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Three {
    int n;
    Set<Integer> set = new HashSet<Integer>();

    public static void main(String args[]) {
        Three three = new Three(10);
        three.display(three.set);
        Set<Integer> test = new HashSet<Integer>();
        Iterator<Integer> it = three.set.iterator();
        while(it.hasNext()) {
            test.add(it.next());
            three.display(test);
            three.display(three.complementarySet(test));
        }

    }

    boolean contains(Set<Integer> s) {
        if (this.set.contains(s))
            return true;
        else 
            return false;
    }

    Set<Integer> complementarySet(Set<Integer> s) {
        if(this.set.contains(s)){
            Set<Integer> result = this.set;
            result.removeAll(s);
            return result;
        }
        else {
            System.out.println("Error: This is not a subset!");
            return null;
        }
    }

    Three() {
        this.n = 3;
        this.randomSet();
    }

    Three(int n) {
        this.n = n;
        this.randomSet();
    }

    void randomSet() {
        while(set.size() < n) {
            set.add((int)(Math.random()*10));
        }
    }

    void display(Set<Integer> s) {
        System.out.println("The set is " + s.toString());
    }
}

Solution

Your problem is in this part:

set.contains(s)

that doesn't do what you think it does, it doesn't take as an argument another Set to see if its members are contained in the firstset. It rather looks if the argument passed it is in the Set.

You need to iterate over the "contained" set and use set.contains(element) for each element in the contained set.



Answered By - morgano
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I Iterate through all possible unique pairs using elements from a set?

 November 07, 2022     itertools, python, python-3.x, set     No comments   

Issue

I'd normally write:

for i in range(len(collection)):
    for j in range(i + 1, len(collection)):
        print(collection[i], collection[j])

That relies on the elements being ordered. How can it be done when using an unordered collection?


Solution

You can use itertools.combinations:

import itertools as it

result = it.combinations(collection, 2)


Answered By - a_guest
Answer Checked By - Katrina (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get the partition with the least number of subsets that respects other partitions?

 November 07, 2022     algorithm, partitioning, set     No comments   

Issue

I have a set of elements and some arbitrary partitions of it.

I want to get a partition that divides the set in the least amount of subsets and "respects" the previous existing partitions. By respecting, I mean:

Let A and B be partitions of set X. Partition A respects B if, for every two elements of X, e and f, if e and f are not in the same subset of X according to partition B, they are also not in the same subset of X according to partition A.

Example:

Set is {1,2,3,4,5,6}

Partition1 is {{1,2,3}, {4,5,6}}

Partition2 is {{1,2}, {3,4}, {5,6}}

A partition that would respect Partition1 and Partition2 (and any other partition) is the "every element in its subset" {{1},{2},{3},{4},{5},{6}} partition. However, I want the partition with the least number of subsets, in this case {{1,2}, {3},{4}, {5,6}}.

Is there an algorithm for this problem? I have googled quite a bit, but couldn’t find anything, probably because I am not being able to describe it well. However, it sounds like a generic problem that should be common.

(another way to describe the problem from this Wikipedia article would be: “how to get the coarsest partition that is finer than a set of arbitrary partitions”)

https://en.wikipedia.org/wiki/Partition_of_a_set


Solution

Here is some working Python:

def partition_to_lookup(partition):
    which_partition = {}
    i = 0
    for part in partition:
        for x in part:
            which_partition[x] = i
        i += 1
    return which_partition

def combine_partitions (partitions):
    lookups = [partition_to_lookup(partition) for partition in partitions]
    reverse_lookup = {}
    for x in lookups[0].keys():
        key = tuple((lookup[x] for lookup in lookups))
        if key in reverse_lookup:
            reverse_lookup[key].add(x)
        else:
            reverse_lookup[key] = {x}

    return list(reverse_lookup.values())

print(combine_partitions([[{1,2,3}, {4,5,6}], [{1,2}, {3,4}, {5,6}]]))

If N is the size of the universe, m is the number of partitions, and k the total number of all sets in all partitions, then this will be O(N*m + k).



Answered By - btilly
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How are lists converted into sets in Python 3? And what's the performance/complexity of this conversion?

 November 07, 2022     big-o, list, python, set, time-complexity     No comments   

Issue

Maybe I missed something, but I couldn't find an answer to this on SO or the Python docs.

Got curious about what actually happens under the hood when we write the following code:

maybe_smaller_set = set(some_huge_list)

Since sets don't have duplicates, I imagine there's something like a list comprehension or some clever trick (maybe using map() or filter()?) that occurs to avoid iterating over everything in some_huge_list.

So my questions are these:

  1. How does Python actually do this conversion from a list instance into a set instance?
  2. And how costly is this conversion in terms of algorithmic complexity (ie, big-O)?

Solution

Python sets are based on hash tables. As such, insertion operations, per-element, are average/expected case O(1), though in pathological cases they can approach O(n).

There is no trick that can be used to avoid iterating the input list though; you can't iterate all the elements without iterating all the elements in a general purpose data structure, no matter the language. The expected case for constructing a set from a list will be O(n), and the theoretical worst case scenario (if literally every element's hash code collides with every other element, but all elements are unique) would be O(n²).

As for how Python does it, it's nothing special; internally, it's roughly equivalent to:

newself = set()
newself.update(iterable)

which is in turn roughly equivalent to:

newself = set()
for elem in iterable:
    newself.add(elem)

it just pushes all the work to the C layer (on the CPython reference interpreter), bypassing the Python layer work such a loop would entail.

To correct an additional misapprehension: There are no clever tricks for map or filter either. In the best case scenario (when called with a built-in function implemented in C), both of them just avoid a little Python level overhead that the equivalent generator expression would entail. But they're fully general purpose; they use no special tricks for list or set inputs or outputs, they just steadily grind through the input iterator, mapping/filtering each element as they're requested (when the map/filter object is itself iterated). They're definitionally O(n).



Answered By - ShadowRanger
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to return named tuples in C#?

 November 07, 2022     c#, datetime, get, set, tuples     No comments   

Issue

I have a property that returns two items of type DateTime. When returning these values I have to reference them as Item1 and Item2. How do I return with custom names e.g.

filter?.DateRanges.From
filter?.DateRanges.To

 

public Tuple<DateTime, DateTime> DateRanges
{
    get
    {
        From = DateTime.Now.AddDays(-1).Date.AddMonths(-1);
        To = DateTime.Now.AddDays(-1).Date;

        if (Preset != 0)
        {
            if (Preset == DatePreset.SpecificRange)
            {
                From = From.Date;
                To = To.Date;
            }
            else
            {
                var dateRange = DateTime.Today.AddDays(-1).GetDateRangeByPreset(Preset);
                From = dateRange.From;
                To = dateRange.To;
            }
        }

        return new Tuple<DateTime, DateTime>(From, To);
    }

usage:

var from = filter?.DateRanges.Item1;
var to = filter?.DateRanges.Item2;

Solution

Like this:

public (DateTime Start, DateTime End) DateRanges
{
    get
    {
        return (DateTime.MinValue, DateTime.MaxValue);
    }
}

Note: This requires a recent version of C# and .Net.

Incidentally, watch out for this usage pattern:

var from = filter?.DateRanges.Start;
var to = filter?.DateRanges.End;

That's inefficient because it causes two identical tuples to be created.

This is better:

var range = filter?.DateRanges;

if (range.HasValue)
{
    var from  = range.Value.Start;
    var to    = range.Value.End;
}

However note that tuples cannot be null (they are value types) so you could write it like so:

if (filter != null)
{
    var range = filter.DateRanges;
    var from  = range.Start;
    var to    = range.End;
    ...
}

ADDENDUM (2022):

Nowadays you can much more simply assign the values of a tuple to local variables. Now we can rewrite the last example above like so:

if (filter != null)
{
    var (from, to) = filter.DateRanges;
    ...
}


Answered By - Matthew Watson
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to force a Set object to contain all values within an enum - TS

 November 07, 2022     enums, set, typescript     No comments   

Issue

I have the following enum:
enum GREETINGS { HELLO = 'Hello', HI = 'Hi' }

I want to create a type for a Set data structure which would force the user to include all of the enum values within it, like below:
type MyGreetings = Set<GREETINGS>

The expected outcome should cause the following line to be highlighted with a warning stating that not all required values are included within the result:
const result: MyGreetings = new Set([GREETINGS.HELLO]);


Solution

One problem is that TypeScript considers Set<GREETINGS.HELLO> to be assignable to / compatible with Set<GREETINGS>; in theory that should mean that if you want Set<GREETINGS> to be assignable to MyGreetings, then by transitivity of assignability, Set<GREETINGS.HELLO> will also be assignable to MyGreetings, and you're stopped before you've begun. But:

The fact that Set<GREETINGS.HELLO> is assignable to Set<GREETINGS> is actually using an intentional hole in the type system: method parameter bivariance. Method parameter bivariance is very useful, but it is not type safe:

const justHello = new Set<GREETINGS.HELLO>([GREETINGS.HELLO]);
const stillJustHello: Set<GREETINGS> = justHello;
stillJustHello.add(GREETINGS.HI) // <-- no error, oops

By "widening" justHello to stillJustHello, the compiler has forgotten that it should not accept any member but GREETINGS.HELLO.

So one way to get closer to what you want is to use the --strictFunctionType compiler option (which is part of the --strict suite of compiler options and is recommended in general) and rewrite at least one Set method signature using a function property type instead of a method signature. Let's look at add() and see the difference:

type Method = { add(x: GREETINGS): void } // method syntax
const m: Method = new Set<GREETINGS.HELLO>(); // okay

type FuncProp = { add: (x: GREETINGS) => void } // function syntax
const f: FuncProp = new Set<GREETINGS.HELLO>(); // error

So let's try something like:

type MyGreetings = Set<GREETINGS> & { add: (g: GREETINGS) => MyGreetings };

If we use that, you get the desired result:

const result: MyGreetings = new Set([GREETINGS.HELLO]); // error!
//  Type 'GREETINGS' is not assignable to type 'GREETINGS.HELLO'

const okay: MyGreetings = new Set([GREETINGS.HELLO, GREETINGS.HI]); // okay

Hooray!


Well, kind of. The compiler really cannot know exactly which values have been passed into a Set. It can infer that new Set(...) is of type Set<X> for some X, but there are ways to manually specify a wider X or get the compiler to infer a wider X. And then all the progress from above is lost.

For example, since a Set<GREETINGS> is allowed to contain just a subset of GREETINGS, someone can do the following manual specification:

const oops: MyGreetings = new Set<GREETINGS>([GREETINGS.HELLO]) // no error

Or someone could get the compiler to infer a union this way:

const alsoOops: MyGreetings = new Set([
  Math.random() < 0.5 ? GREETINGS.HELLO : GREETINGS.HI
]); // no error

Neither of those can be an error; the value on the right hand side of the equals sign is a Set<GREETINGS>. And you need Set<GREETINGS> to be assignable to MyGreetings, so the assignments are also not errors. There's not much that can be done about this.

If in practice you don't think someone will create a set in these or other pathological ways, then maybe you can use MyGreetings. Otherwise, if you really need to guarantee something, you should consider changing your design in some way. But this is probably out of scope for the question, so I'll stop there.


Playground link to code (tested and working for typescript version 3.5.1 and higher)



Answered By - jcalz
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to force a Set object to contain all values within an enum - TS

 November 07, 2022     enums, set, typescript     No comments   

Issue

I have the following enum:
enum GREETINGS { HELLO = 'Hello', HI = 'Hi' }

I want to create a type for a Set data structure which would force the user to include all of the enum values within it, like below:
type MyGreetings = Set<GREETINGS>

The expected outcome should cause the following line to be highlighted with a warning stating that not all required values are included within the result:
const result: MyGreetings = new Set([GREETINGS.HELLO]);


Solution

One problem is that TypeScript considers Set<GREETINGS.HELLO> to be assignable to / compatible with Set<GREETINGS>; in theory that should mean that if you want Set<GREETINGS> to be assignable to MyGreetings, then by transitivity of assignability, Set<GREETINGS.HELLO> will also be assignable to MyGreetings, and you're stopped before you've begun. But:

The fact that Set<GREETINGS.HELLO> is assignable to Set<GREETINGS> is actually using an intentional hole in the type system: method parameter bivariance. Method parameter bivariance is very useful, but it is not type safe:

const justHello = new Set<GREETINGS.HELLO>([GREETINGS.HELLO]);
const stillJustHello: Set<GREETINGS> = justHello;
stillJustHello.add(GREETINGS.HI) // <-- no error, oops

By "widening" justHello to stillJustHello, the compiler has forgotten that it should not accept any member but GREETINGS.HELLO.

So one way to get closer to what you want is to use the --strictFunctionType compiler option (which is part of the --strict suite of compiler options and is recommended in general) and rewrite at least one Set method signature using a function property type instead of a method signature. Let's look at add() and see the difference:

type Method = { add(x: GREETINGS): void } // method syntax
const m: Method = new Set<GREETINGS.HELLO>(); // okay

type FuncProp = { add: (x: GREETINGS) => void } // function syntax
const f: FuncProp = new Set<GREETINGS.HELLO>(); // error

So let's try something like:

type MyGreetings = Set<GREETINGS> & { add: (g: GREETINGS) => MyGreetings };

If we use that, you get the desired result:

const result: MyGreetings = new Set([GREETINGS.HELLO]); // error!
//  Type 'GREETINGS' is not assignable to type 'GREETINGS.HELLO'

const okay: MyGreetings = new Set([GREETINGS.HELLO, GREETINGS.HI]); // okay

Hooray!


Well, kind of. The compiler really cannot know exactly which values have been passed into a Set. It can infer that new Set(...) is of type Set<X> for some X, but there are ways to manually specify a wider X or get the compiler to infer a wider X. And then all the progress from above is lost.

For example, since a Set<GREETINGS> is allowed to contain just a subset of GREETINGS, someone can do the following manual specification:

const oops: MyGreetings = new Set<GREETINGS>([GREETINGS.HELLO]) // no error

Or someone could get the compiler to infer a union this way:

const alsoOops: MyGreetings = new Set([
  Math.random() < 0.5 ? GREETINGS.HELLO : GREETINGS.HI
]); // no error

Neither of those can be an error; the value on the right hand side of the equals sign is a Set<GREETINGS>. And you need Set<GREETINGS> to be assignable to MyGreetings, so the assignments are also not errors. There's not much that can be done about this.

If in practice you don't think someone will create a set in these or other pathological ways, then maybe you can use MyGreetings. Otherwise, if you really need to guarantee something, you should consider changing your design in some way. But this is probably out of scope for the question, so I'll stop there.


Playground link to code (tested and working for typescript version 3.5.1 and higher)



Answered By - jcalz
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to reliably check an object is an EcmaScript 6 Map/Set?

 November 07, 2022     collections, dictionary, ecmascript-6, javascript, set     No comments   

Issue

I just want to check that an object is a Map or Set and not an Array.

to check an Array I'm using lodash's _.isArray.

function myFunc(arg) {
  if (_.isArray(arg)) {
    // doSomethingWithArray(arg)
  }

  if (isMap(arg)) {
    // doSomethingWithMap(arg)
  }

  if (isSet(arg)) {
    // doSomethingWithSet(arg)
  }
}

If I were to implement isMap/isSet, what does it need to look like? I'd like for it to be able to catch subclasses of Map/Set if possible as well.


Solution

The situation is similar to pre-ES5 methods to detect arrays properly and reliably. See this great article for the possible pitfalls of implementing isArray.

We can use

  • obj.constructor == Map/Set, but that doesn't work on subclass instances (and can easily be deceived)
  • obj instanceof Map/Set, but that still doesn't work across realms (and can be deceived by prototype mangling)
  • obj[Symbol.toStringTag] == "Map"/"Set", but that can trivially be deceived again.

To be really sure, we'd need to test whether an object has a [[MapData]]/[[SetData]] internal slot. Which is not so easily accessible - it's internal. We can use a hack, though:

function isMap(o) {
    try {
        Map.prototype.has.call(o); // throws if o is not an object or has no [[MapData]]
        return true;
    } catch(e) {
        return false;
    }
}
function isSet(o) {
    try {
        Set.prototype.has.call(o); // throws if o is not an object or has no [[SetData]]
        return true;
    } catch(e) {
        return false;
    }
}

For common use, I'd recommend instanceof - it's simple, understandable, performant, and works for most reasonable cases. Or you go for duck typing right away and only check whether the object has has/get/set/delete/add/delete methods.



Answered By - Bergi
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to use LINQ to find all combinations of n items from a set of numbers?

 November 07, 2022     algorithm, c#, linq, logic, set     No comments   

Issue

I'm trying to write an algorithm to select all combinations of n values from a set of numbers.

For instance, given the set: 1, 2, 3, 7, 8, 9

All combinations of 2 values from the set is:

(1, 2), (1, 3), (1, 7), (1, 8), (1, 9), (2, 3), (2, 7), (2, 8), (2, 9), (3, 7), (3, 8), (3, 9), (7, 8), (7, 9), (8, 9)

And 3 is:

(1, 2, 3), (1, 2, 7), (1, 2, 8), (1, 2, 9), (1, 3, 7), (1, 3, 8), (1, 3, 9), (1, 7, 8), (1, 7, 9), (1, 8, 9), (2, 3, 7), (2, 3, 8), (2, 3, 9), (2, 7, 8), (2, 7, 9), (2, 8, 9), (3, 7, 8), (3, 7, 9), (3, 8, 9), (7, 8, 9)

etc!

I'm currently using methods to to yield return sets of combinations of 2, 3 and 4 values, but it seems to me this could be generalised in a LINQ query.


Solution

Usage:

var results = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.DifferentCombinations(3);

Code:

public static class Ex
{
    public static IEnumerable<IEnumerable<T>> DifferentCombinations<T>(this IEnumerable<T> elements, int k)
    {
        return k == 0 ? new[] { new T[0] } :
          elements.SelectMany((e, i) =>
            elements.Skip(i + 1).DifferentCombinations(k - 1).Select(c => (new[] {e}).Concat(c)));
    }
}


Answered By - user109260
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to add user input to dictionary

 November 07, 2022     dictionary, python, set     No comments   

Issue

s = set()
i = 0
while True:
    user_input = input("enter words: ")
    for words in user_input.strip().split():
        words_from_list = words.strip().split()
        for x in words_from_list:
            s.add(x) 
    for i in s:
    print(i)    

the code above should show output like below

enter text: how are you dear

how 1

are 2

you 3

dear 4

enter text: how was your morning

how 1

your 5

was 6

morning 7

dear 4

random sequence is due to set the repeated element should have same sequence number


Solution

I assume you wanted to do this:

s = set()
i = 0
while True:
    user_input = input("enter words: ")
    for words in user_input.strip().split():
        words_from_list = words.strip().split()
        for x in words_from_list:
            s.add(x)
    for i in s:
        print(i)


Answered By - NoBlockhit
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to find the maximum in std::set< pair<int, int> > in a given range?

 November 07, 2022     c++, c++11, set, stl     No comments   

Issue

I have a set of pairs, and I want to find the maximum number in the second entry of the pair between l and r inclusive.

This is what the set looks like: myset = [(0,2),(1,1),(2,4),(3,0),(4,3)]

Here is what I have tried:

#include <iostream>
#include <set>
using namespace std;

#define INPUT1(x)  scanf("%d", &x)
#define INPUT2(x, y)  scanf("%d%d", &x, &y)
#define OUTPUT1(x) printf("%d\n", x);

bool cmp(pair<int, int> A, pair<int, int> B) {
    return A.second < B.second;
}

int main(int argc, char const *argv[]) {
    int n;
    INPUT1(n);

    set< pair<int,int> > myset;
    set< pair<int,int> >::iterator it;

    for (int i = 0; i < n; i++) {
        int val;
        INPUT(val);
        myset.insert(make_pair(i, val));
    }

    int l, r;
    INPUT2(l, r);
    int max = std::max_element(myset.begin()+l, myset.begin()+r+1, cmp)->second;
    OUTPUT1(max);
}

This doesn't work but for l = 1 and r = 3 I want is for max to equal 4.

I get the following error:

invalid operands to binary expression

('iterator' (aka '__tree_const_iterator<std::__1::pair<int, int>, std::__1::__tree_node<std::__1::pair<int, int>, void *> *, long>') and 'int')

Solution

You cannot use std::max_element in such manner. The reason is that std::set provides bidirectional iterators, not random access iterators, so the things like myset.begin()+l are forbidden.

You should use something like this:

auto mx = std::numeric_limits<int>::min();

auto first = std::cbegin(myset);
std::advance(first, lf);

auto last = std::cbegin(myset);
std::advance(last, rg + 1);

for (auto it = first; it != std::cend(myset) && it != last; ++it) {
    mx = std::max(mx, it->second);
}


Answered By - Edgar Rokjān
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get index of an item in java.util.Set

 November 07, 2022     java, set     No comments   

Issue

I know the differences between Set and List(unique vs. duplications allowed, not ordered/ordered, etc). What I'm looking for is a set that keeps the elements ordered(that's easy), but I also need to be able to recover the index in which an element was inserted. So if I insert four elements, then I want to be able to know the order in which one of them was inserted.

MySet<String> set = MySet<String>();
set.add("one");
set.add("two");
set.add("three");
set.add("four");

int index = set.getIndex("two");

So at any given moment I can check if a String was already added, and get the index of the string in the set. Is there anything like this, or I need to implement it myself?


Solution

A small static custom method in a Util class would help:

 public static <T> int getIndex(Set<T> set, T value) {
   int result = 0;
   for (T entry:set) {
     if (entry.equals(value)) return result;
     result++;
   }
   return -1;
 }
  

If you need/want one class that is a Set and offers a getIndex() method, I strongly suggest to implement a new Set and use the decorator pattern:

 public class IndexAwareSet<T> implements Set {
   private Set<T> set;
   public IndexAwareSet(Set<T> set) {
     this.set = set;
   }

   // ... implement all methods from Set and delegate to the internal Set

   public int getIndex(T entry) {
     int result = 0;
     for (T entry:set) {
       if (entry.equals(value)) return result;
       result++;
     }
     return -1;
   }
 }


Answered By - Andreas Dolk
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is the role of greater <int> in set?

 November 07, 2022     c++, set, stl     No comments   

Issue

While declaring a set,

set <int, greater <int> > gquiz1;

why do we use greater <int>? What purpose does it serve?


Solution

std::set is a container that contains an ordered set of objects.

The ordering of the objects is determined by the second argument. By default, it is std::less<Key>. See the definition of std::set for additional details. However, you can override the default argument by using your own Compare type as the second argument, as you have done in your posted code.

E.g.

std::set<int> set1; // Use default compare class, std::less<int>
set1.insert(10);
set1.insert(5);
set1.insert(7);

The order of the objects in the above container will be 5, 7, and 10. The objects in the container are sorted in increasing orer.

If you use

std::set<int, std::greater<int>> set2;
set2.insert(10);
set2.insert(5);
set2.insert(7);

The order of the objects in the above container will be 10, 7, and 5. The objects in the container are sorted in decreasing orer.



Answered By - R Sahu
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to modify single object inside dict values stored as a set?

 November 07, 2022     dictionary, python, python-3.x, set     No comments   

Issue

I have a dictionary which represents graph. Key is Node class and values are set of Nodes. So it has this structure: dict[Node] = {Node, Node, Node}

class Node:

def __init__(self, row, column, region):
    self.id = f'{str(row)}-{str(column)}'
    self.region = region
    self.visited = False

In code below I need to update visited property of Node class.

        while nodes_queue:
        current_node = nodes_queue.pop()

        for edge in self.map[current_node]: 
            if edge.region == root.region and not edge.visited:
                edge.visited = True # Not updated!
                nodes_queue.append(edge)

But it looks like I get view of Node objects instead of actual objects. When I update visited property in for loop and get it from next iteration, the property is still set to False


Solution

I've figured it out. I was storing different Node objects as key and what was in values set in my dictionary. I created context of all Nodes and get Node from there by its id.

def get_node_from_context(self, row, column, region):
        node = Node(row, column, region)

        if node not in self.__graph_context__:
            self.__graph_context__[node] = node
        else:
            node = self.__graph_context__[node]

        return node


Answered By - tojzke
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing