簡體   English   中英

如何在 arrays 的列表(數組)中找到最頻繁的(n 個元素)組合

[英]How to find the most Frequent (n-elements) Combinations in list(array) of arrays

我試圖找到一種方法來列出 arrays 列表中最常見的組合。 它必須至少有兩個元素在 arrays 之一中出現不止一次。 然后按數字順序顯示最頻繁的。 假設我有一個 arrays 列表,我想知道最常見的組合。

列表=:

Array (4) ["a", "b", "c", "d"]
Array (4) ["b", "c", "d"]
Array (4) ["c", "d"]
Array (4) ["a", "b"]
Array (4) ["a", "c", "d"]

期望的結果:

No of occur - Elements
4 - ["c","d"]
2 - ["b","c"]; ["a","b"]; ["a","c","d"]

如何在所有這些 arrays 中獲得最常見的元素組合?

在這種情況下,它是 ["c","d"],因為它們出現了 4 次。

數組中兩個或多個元素的最常見組合。

謝謝。

如果您期望的唯一元素數量足夠少,您可以使用以下方法:

  • 使用數據集中的獨特元素確定所有可能的組合。 在這種情況下abcdabcabdbcdab等。
  • 對於每個組合,檢查有多少輸入 arrays 包含所有組合的字符

隨着數據中有更多獨特元素(例如從 a 到 z 的所有字符),可能的組合數量將迅速增加。

如果是這種情況,但單個列表仍然很小,我建議不要查看所有唯一組合,而是使用實際出現在數據中的組合。

 //// Utils // Get all unique sets of a size const allSets = (xs, size) => size === 1? xs: xs.flatMap( (x, i) => allSets(xs.slice(i + 1), size - 1).map(tail => [x, ...tail])) // Get a range of ints between two values const range = (from, to) => Array.from({ length: to - from + 1 }, (_, i) => from + i); // Get all unique values from an array const uniques = xs => Array.from(new Set(xs)); //// App const input = [ ["a", "b", "c", "d"], ["b", "c", "d"], ["c", "d"], ["a", "b"], ["a", "c", "d"]]; const uniqueChars = uniques(input.flat()); const combinations = range(2, 4).flatMap(size => allSets(uniqueChars, size)); // Create sets so we can use.has instead of.includes const inputSets = input.map(xs => new Set(xs)); // For all combinations, check how many sets include all of the characters const combinationScores = combinations.map(combo => [ // Check how many sets contain all the chars of this combo inputSets.filter(s => combo.every(x => s.has(x))).length, // Join the set for easy logging combo.join("") ]) // Sort by appearance count.sort( ([c1], [c2]) => c2 - c1); // Print to console console.log(combinationScores.join("\n"));

暫無
暫無

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

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