Use js to implement those data structures 10 (collection 02-collection operations)

  In the previous article, we implemented a custom set collection class together. So in this article, let's add some operation methods to the set class. So before we start, it is still necessary to explain what the operations of sets are. It is convenient for us to understand the code more quickly.

  1. Union: For the given two sets, return a new set containing all the elements in the two sets. Note that there will be no duplicate values ​​in the collection.  

  2. Intersection: For the given two sets, return a new set containing the elements common to both sets.

  3. Difference Set: For a given set, return a new set containing all elements that exist in the first set and do not exist in the second set. Simply put, I have elements that you don't have.

  4. Verify that a given set is a subset of another set.

  Here we will not repeat the mathematical calculation method of the set operation in detail. If you are interested or have forgotten, you can Baidu. Then we officially start the operation method of the collection.

1. Union

// Union operation 
this .union = function (otherSet) {
     // A new set that stores the elements of the two sets, which we will return as the return value later. 
    let unionSet = new Set();
     // values ​​is an array list of the current set 
    let values ​​= this .values();
     // loop adding 
    for (let i = 0; i < values.length; i++ ) {
        unionSet.add(values[i]);
    }
    // Re-copy values 
    ​​values ​​= otherSet.values();
     // Recycle the values ​​of otherSet into the unionSet, since our add will not add duplicate values, naturally there will be no duplicate values ​​in the unionSet 
    for (let i = 0; i < values. length; i++ ) {
        unionSet.add(values[i]);
    }

    return unionSet;
}

  We found that the operation of union is actually very simple, that is, to declare a new set, and then store the values ​​in the two setsA and setB into the new unionSet by looping. not complicated at all

let setA = new Set();
setA.add ( 1 );
setA.add ( 2 );
setA.add ( 3 );
let setB = new Set();
setB.add(3);
setB.add(4);
setB.add(5);
setB.add(6);


let unionAB = setA.union(setB);
console.log(unionAB.values());// [1, 2, 3, 4, 5, 6]

2. Intersection

// Intersection operation 
this .intersection = function (otherSet) {
  let intersectionSet = new Set();

  let values = this.values();
  for (let i = 0; i < values.length; i++) {
      if(otherSet.has(values[i])) {
          intersectionSet.add(values[i])
      }
  }

  return intersectionSet;
}

  The intersection operation is actually very simple. In one sentence, it is to check whether the elements in setA are also in setB, and if so long, they are stored in intersectionSet. Just like we want to find out if two arrays have the same element.

let setC = new Set();
setC.add(5);
setC.add(6);
setC.add(7);

let setD = new Set();
setD.add(5);
setD.add(7);
setD.add(4);
setD.add(8);

let intersectionSetCD = setC.intersection(setD);
console.log(intersectionSetCD.values());//[5,7]

Third, the difference set

// Difference operation 
this .difference = function (otherSet) {
  let differenceSet = new Set();

  let values ​​= this .values();
   for (let i = 0; i < values.length; i++ ) {
       // It's just that the judgment here is not (!) compared to the intersection operation 
      if (! otherSet.has(values [i])) {
          differenceSet.add(values[i])
      }
  }

  return differenceSet;
}

  The operation of subtraction is very similar to that of union. The union is the element that needs to be present in both sets ( you have it and I have it ), and the difference set is the element that exists in setA but not in setB (you have it and I don't).

  So we just need to change the code for intersection a little bit.

let setM = new Set();
setM.add ( 5 );
setM.add ( 6 );
setM.add ( 7 );

let setN = new Set();
setN.add(5);
setN.add(7);
setN.add(4);
setN.add(8);


let differenceSetMN = setM.difference(setN);
console.log(differenceSetMN.values());//[6]

4. Subset

//子集操作
this.subset = function (otherSet) {
    if(this.size() > otherSet.size()) {
        return false;
    } else {
        let values = this.values();
        for (let i = 0; i < values.length; i++) {
            if(!otherSet.has(values[i])) {
                return false;
            }
        }
        return true;
    }
}

  In fact, there is no good explanation for the subset operation, but it should be noted that if the subset of setA is setB, then the number of elements of setA must be greater than or equal to setB. Otherwise setB cannot be a subset of setA. So we judge at the very beginning whether the size of the element conforms to this definition.

  Then if it matches, we are traversing the elements of the entire setB to determine whether they exist in setA. As long as there are non-existent elements, we will directly return false. If the traversal ends, we will return true.

let setX = new Set();
setX.add(1);
setX.add(2);

let setY= new Set();
setY.add ( 1 );
setY.add ( 2 );
setY.add ( 3 );

let setZ= new Set();
setZ.add(2);
setZ.add(3);
setZ.add(4);

console.log(setX.subset(setY));//true
console.log(setX.subset(setZ));//false

  Here we have introduced the operation of the set, is it very simple? So let's take a look at what the ES6 native set class looks like.

ES6 native Set class

  Let's first look at a simple example of the native set class:

let set = new Set();
set.add(1);
console.log(set.values());//SetIterator {1}
set.add(2);
console.log(set.has(1));//true
console.log(set.size)//2
console.log(set.delete(1));//true
console.log(set.size)//1
console.log(set.has(1));//false
console.log(set.has(2));//true

  The native Set class has methods such as has(), add(), delete(), and clear(). It also has traversal methods such as values(), keys(), entries(), forEach(), and a size attribute. Each attribute method will not be introduced in detail here. If you want to learn more, you can check it yourself.

  So let's see how to use the native Set class to manipulate collections.

let setA = new Set();
setA.add ( 1 );
setA.add ( 2 );
setA.add ( 3 );

let setB = new Set();
setB.add(2);
setB.add(3);
setB.add(4);



// Simulate union operation 
let unionAb = new Set();
 // In fact, the principle is the same as our custom union operation, traverse two sets and add their elements to unionAb 
// for...of This operation is also the ES6 loop traversal method. 
for (let x of setA) unionAb.add(x);
 for (let x of setB) unionAb.add(x);
console.log(unionAb.values())//SetIterator {1, 2, 3, 4}

// Simulate the intersection operation 
// Simulating the intersection operation requires creating a helper function to generate a new set containing elements that have both setA and setB. 
let intersetion = function (setA,setB) {
    let intersetionSet = new Set();

    for(let x of setA) {
        if(setB.has(x)) {
            intersetionSet.add(x);
        }
    }

    return intersetionSet;
}

let intersetionAb = intersetion(setA,setB);
console.log(intersetionAb.values())//SetIterator {2, 3}


// Simulate the difference operation 
// Similarly, it is very similar to the intersection operation, but the judgment condition is just the opposite. 
let difference = function (setA,setB) {
    let differenceSet = new Set();

    for(let x of setA) {
        if(!setB.has(x)) {
            differenceSet.add(x);
        }
    }

    return differenceSet;
}

let differenceAb = difference(setA,setB);
console.log(differenceAb.values())//SetIterator {1}

  When we finished writing the ES6 native Set class to simulate the set operation, we found that it was very similar to our custom set operation method. It's just that we use the ES6 native interface. You can try to compare these two types of code. deepen impression.

  The collection is complete here. Looking back at the code, we found that the various operation methods of collections are often applied in our actual work, but we are operating with arrays and do not pay much attention to these details. For example, the union operation, we must have used it when merging two arrays. For example, the intersection operation, we will use it when finding common elements in two arrays. So in fact, we have used or often use these ideas similar to set operations in our work.

  

  Finally, due to my limited level, my ability is still far from that of the Great God. If there are mistakes or unclear points, I hope everyone will give me some advice and corrections. thank you very much!

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324645381&siteId=291194637