簡體   English   中英

如何檢查數組元素是否與某些模式匹配(例如:XXXXYY)?

[英]How to check if array elements match some pattern (eg:XXXXYY)?

例如,我有數組:

[1,2,3,2,2,2,1,2,3]

,它匹配模式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); 

但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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM