oco*_*mfd 5 javascript arrays algorithm
例如,我有数组:
[1,2,3,2,2,2,1,2,3]
Run Code Online (Sandbox Code Playgroud)
,它匹配模式XXXXYY,因为它有(至少)四个'2'和两个'1',但我的问题是,如何检查数组是否匹配这样的模式?我试过了:
const arr=[1,2,3,2,2,2,1,3,2];
const pattern=[4,2];
let m=new Map();
for(const num of arr){
if(!m[num]){
m[num]=0;
}
m[num]++;
}
let i=0;
let isMatch=true;
for(const key in m){
if(m[key]<pattern[i]){
isMatch=false;
}
i++;
}
console.log(isMatch);Run Code Online (Sandbox Code Playgroud)
但isMatch是假的.有没有更简单的方法来做到这一点?
您可以对值进行计数,然后获取排序后的计数并检查排序后的模式。
var DESC = (a, b) => b - a,
array = [1, 2, 3, 2, 2, 2, 1, 3, 2],
pattern = [4, 2],
count = Array
.from(array.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map).values())
.sort(DESC),
check = pattern
.sort(DESC)
.every((c, i) => count[i] >= c);
console.log(check);
console.log(count);Run Code Online (Sandbox Code Playgroud)