javascript算法學(xué)習(xí)打卡(第一周)

之前因為工作原因接觸了很多有意思的算法知識,為了鞏固大家的算法基礎(chǔ)和編程能力,筆者將開展為期2個月的算法學(xué)習(xí)打卡, 每周3-5次算法訓(xùn)練, 并附有算法題的答案, 供大家學(xué)習(xí)參考. 接下來我們復(fù)盤第一周的算法打卡內(nèi)容.
1.有一個數(shù)組arr = [a1, a2, a3, b1, b2, b3, c1, c2, c3...], 通過算法將數(shù)組進行拆分, 轉(zhuǎn)化為如下格式的數(shù)組a1, b1, c1], [a2, b2, c2], [a3, b3, c3]并實現(xiàn)通用公式
/**
* arr 待排序數(shù)組
* result 計算的結(jié)果數(shù)組
*/
function rangeArr(arr = [], result = []) {
arr.forEach(item => {
let i = /\d*$/.exec(item)[0]
result[i] ? result[i].push(item) : (result[i] = [item])
})
return result.filter(Boolean)
}
網(wǎng)友優(yōu)質(zhì)答案:

2.假設(shè)集合A={a, b},集合B={0, 1, 2},則兩個集合的笛卡爾積為{(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}。求當(dāng)A={a, b, ..., n}, B={0, 1, 2, ..., n}時的笛卡爾積.
笛卡爾乘積是指在數(shù)學(xué)中,兩個集合X和Y的笛卡尓積,又稱直積,表示為X × Y,第一個對象是X的成員而第二個對象是Y的所有可能有序?qū)Φ钠渲幸粋€成員 。

/*
* @Author: Mr Jiang.Xu
* @Date: 2019-08-31 00:05:33
* @Last Modified by: Mr Jiang.Xu
* @Last Modified time: 2019-08-31 00:05:33
*/
function cartesian(arr) {
if (arr.length < 2) return arr[0] || [];
return [].reduce.call(arr, function (col, set) {
let res = [];
col.forEach(c => {
set.forEach(s => {
let t = [].concat(Array.isArray(c) ? c : [c]);
t.push(s);
res.push(t);
})
});
return res;
});
}
3.原生js實現(xiàn)一個Set數(shù)據(jù)類型, 并實現(xiàn)集合的差集, 并集, 補集, 交集
// 創(chuàng)建集合,并實現(xiàn)交集,差集,補集,并集function MySet() {let items = {}// 判斷值是否存在this.has = function(val) {return val in items}// 添加this.add = function(val) {if(!this.has(val)) {items[val] = valreturn true}return false}// 移除this.remove = function(val) {if(this.has(val)) {delete items[val]return true}return false}// 清空this.clear = function() {items = {}}// 大小this.size = function() {return Object.keys(items).length}// 取值this.values = function() {return Object.keys(items)}// 并集this.union = function(otherSet) {let unionSet = new Set()let values = this.values()for(let i=0; i < values.length; i++) {unionSet.add(values[i])}values = otherSet.values()for(let i=0; i < values.length; i++) {unionSet.add(values[i])}return unionSet}// 交集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}// 差集this.difference = function(otherSet) {let differenceSet = new Set()let values = this.values()for(let i = 0; i < values.length; i++) {if(!otherSet.has(values[i])) {differenceSet.add(values[i])}}return differenceSet}// 子集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}}}

評論
圖片
表情
