Code Monkey home page Code Monkey logo

Comments (2)

lamelamb avatar lamelamb commented on August 13, 2024

1 实现一个去重算法, a,b 2个 concat 后 形成新数组,去重就为并集合
2 1 的去重被抛弃的数装进一个新的数组,再次去重就是交集
3 分别用a,b 除去 交集,就是他们各自的差集
4 a,b 相对1 的去重后新数组 的差就是补集

from daily.

MMmaXingXing avatar MMmaXingXing commented on August 13, 2024

实现数组的并、交、差、补集四个方法

释意

并集: 若A、B是集合,那么并集就是所有A的元素和所有B的元素

交集: 若A、B是集合,那么所有集合A中,集合B中所共有的元素组成的集合,叫做交集

补集:设S是一个集合,A是S的一个子集,由S中所有不属于A元素组成的集合,叫做子集A在集合S中的绝对补集。补集分为绝对补集和相对补集。

差集: 有两个集合,集合A、集合B,差集就是集合A-集合B

差集和补集的区别:补集要求子集A必须是S的一个子集,差集是两个集合之间的差。

如图: 
'关系图'

代码实现

// 交集: 
let InterSection = function (arr1, arr2) {
    return arr1.filter((v) => arr2.indexOf(v) > -1);
}

// 并集: 
let Union = function (arr1, arr2) {
    return arr1.concat(arr2.filter((v) => !(arr1.indexOf(v) > -1)));
}

// 补集:
let Complement = function (arr1, arr2) {
    let all
    return arr1.filter((v) => !(arr2.indexOf(v) > -1));
}

// 差集:
let DifferenceSet = function (arr1, arr2) {
    return arr1.filter((v) => arr2.indexOf(v) == -1);
}

// console.log(InterSection([1,2,3,4,5], [3,4,6,7]));
// console.log(Union([1,2,3,4,5], [3,4,6,7]));
// console.log(Complement([1,2,3,4,5], [3,4,6,7]));
// console.log(DifferenceSet([1,2,3,4,5], [3,4,6,7]));

from daily.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.