zoukankan      html  css  js  c++  java
  • 求集合的幂集

    觉得这个函数很有意思,所以把理解写下

    幂集:由集合所有子集组成的集合

    function powerSet(a){
        const powerSet = new Set(new Set());  //空集
        for(const aValue of a){
            for(const set of new Set(powerSet)){
                powerSet.add(new Set(set).add(aValue));
            }
        }
        return powerSet;
    }
    

    代码解析:
    第2行代码是添加空集,
    如果想在创建的同时初始化实例,则可以给 Set 构造函数传入一个可迭代对象,其中需要包含插入到新集合实例中的元素
    const powerSet = new Set(new Set());等价于const powerSet = new Set(new Set([]));
    传入的可迭代对象中的元素是要插入到新实例里去的。

    //注意看s1和s2
    const s1 = new Set([1]);
    const s2 = new Set(s1);
    s2;
    //Set(1) {1}[[Entries]]0: 1 value: 1 size: (...)__proto__: Set
    s1;
    //Set(1) {1}[[Entries]]0: 1 value: 1 size: (...) __proto__: Set
    const s3 = new Set();
    const s4 = new Set([]);
    s3;
    //Set(0) {}
    //[]
    s4;
    //Set(0) {}
    //[]
    

    假如a = [1,2,3]
    回到幂集函数上,第2行代码的powerSet[[]]
    第1次外循环,aValue = 1,
    第1次内循环,new Set(powerSet)[[]](把[]作为插入到新实例的元素),于是set为[]
    然后第5行代码,new Set(set)等价于new Set([]),即[]。然后add(aValue)[1],然后powerSet[[],[1]]

    幂集生成顺序:

    //以a = [1,2,3]
    [[]]
    [[],[1],[2],[1,2]]
    [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
    

    感谢观看!

  • 相关阅读:
    P2P编程(十)
    9.25
    9.22
    pycharm常用快捷命令
    sublime常用快捷方式
    3.1
    总想听你说起不曾喜欢你
    1.1
    python 网络编程和并发编程题
    知识点梳理 网络基础
  • 原文地址:https://www.cnblogs.com/liulangbxc/p/14684145.html
Copyright © 2011-2022 走看看