Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript 求 N 个数组的笛卡尔积 #14

Open
sunhengzhe opened this issue Apr 14, 2018 · 3 comments
Open

javascript 求 N 个数组的笛卡尔积 #14

sunhengzhe opened this issue Apr 14, 2018 · 3 comments

Comments

@sunhengzhe
Copy link
Member

sunhengzhe commented Apr 14, 2018

给定 N 个数组,求出这些数组的笛卡尔积

function getArranging( /* listA, listB, ... */){
      //TODO - 返回 listA × listB × ...
}

const a = [0, 1];
const b = [3, 4, 5];
const c = [6, 7];

// test
expect(getArranging( a, b )).to.eql(
    [
        [0, 3], [0, 4], [0, 5],
        [1, 3], [1, 4], [1, 5]
    ]
);

expect(getArranging( a, b, c )).to.eql(
    [
        [0,3,6], [0,3,7],
        [0,4,6], [0,4,7],
        [0,5,6], [0,5,7],
        [1,3,6], [1,3,7],
        [1,4,6], [1,4,7],
        [1,5,6], [1,5,7]
    ]
);
@yinkaihui
Copy link

function getArranging(...args) {
  return args.reduce(function (a, b) {
    const curRes = []
    a.forEach(x => {
      b.forEach(y => {
        curRes.push([].concat(x, y))
      })
    })
    return curRes
  }, [[]])
}

@iLove-Coding
Copy link

iLove-Coding commented Apr 15, 2018

       function getArranging() {
            let result = arguments[0];
            for (let i = 1; i < arguments.length; i++) {
                result = utilFn(result, arguments[i]);
            }
            return result;
        }

        function utilFn(arr1, arr2) {
            let arr = [];
            arr1.map(elt1 => {
                arr2.map(elt2 => {
                    arr.push([].concat(elt1, elt2));
                })
            });
            return arr;
        }

@sunhengzhe
Copy link
Member Author

😂 我的思路跟 @yinkaihui 是一样的,另外补充一个递归的写法,盗用一下 @iLove-Coding 的 utilFn

function getArranging(listA, listB, ...rest) {
    if (!listB) {
        return listA;
    }

    return getArranging(utilFn(listA, listB), ...rest);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants