permutations and combinations in js All In One
js 中的排列組合
概念
permutation
排列, 如果次序
重要就叫排列, 排列是有序
的組合。✅
combination
組合, 如果次序
不重要就叫組合。
兩種
基本排列
:
可重複
:如,密碼鎖的密碼,可以是 666
不可重複
:如,密碼鎖的密碼,可以是 369
有兩種組合(次序不重要):
可重複
:如, 口袋裏的硬幣 (5角, 5角, 1元,1元)
不可重複
:如, 彩票號碼,30選7 (1,3,5,7,9,11,13)
https://www.shuxuele.com/combinatorics/combinations-permutations.html
階乘
!(一種不可重複
的排列✅)
例子:4!
是 4 x 3 x 2 x 1 的簡寫
https://www.shuxuele.com/numbers/factorial.html
彩票
https://www.shuxuele.com/data/lottery.html
七樂彩
採用組合式玩法,從01—30共30個
號碼中選擇7個
號碼組合爲一注投注號碼。
https://www.cwl.gov.cn/fcpz/yxjs/qlc/
demos
/*
permutations & combinations
排列 & 組合
https://leetcode.com/problems/3sum/
給定一個數字數組,找出有三個元素爲一組構成的所有不重複的子數字數組!
*/
// const arr = [1,2,3]
const arr = [1,2,3,4,5]
const arrs = [];
const map = new Map();
for (let i = 0; i < [arr.length - 2]; i++) {
for (let j = i + 1; j < [arr.length - 1]; j++) {
for (let k = i + 2; k < arr.length; k++) {
const value = [arr[i], arr[j], arr[k]];
const key = value.sort((a, b) => a - b > 0 ? 1 : -1).join('');
// 排序,序列化,去除重複組合,如 134 & 143
if(!map.has(key)) {
map.set(key, [...map.get(key), value]);
// map.set(key, value);
if(j !== k) {
// 去除重複數字,如 133
arrs.push(value);
}
}
}
}
}
console.log(`arrs =`, arrs)
/*
$ node ./permutations.js
arrs = [
[ 1, 2, 3 ], [ 1, 2, 4 ],
[ 1, 2, 5 ], [ 1, 3, 4 ],
[ 1, 3, 5 ], [ 1, 4, 5 ],
[ 2, 3, 4 ], [ 2, 3, 5 ],
[ 2, 4, 5 ], [ 3, 4, 5 ]
]
*/
// // const arr = [1,2,3]
// const arr = [1,2,3,4,5]
// const arrs = [];
// for (let i = 0; i < [arr.length - 2]; i++) {
// for (let j = i + 1; j < [arr.length - 1]; j++) {
// for (let k = i + 2; k < arr.length; k++) {
// let f = arr[i];
// let s = arr[j];
// let t = arr[k];
// // console.log(`[f,s,t] =`, [f,s,t], `?`, f,s,t)
// // arrs.push([f,s,t]);
// if(s !== t) {
// arrs.push([f,s,t]);
// }
// }
// }
// }
// console.log(`arrs =`, arrs)
test 驗證
組合與排列計算器
Combinations without repetition (n=5
, r=3
)
Using Items: 1,2,3,4,5
List has 10 entries.
[1,2,3],[1,2,4],[1,2,5],[1,3,4],[1,3,5],[1,4,5],[2,3,4],[2,3,5],[2,4,5],[3,4,5]
https://www.shuxuele.com/combinatorics/combinations-permutations-calculator.html
(🐞 反爬蟲測試!打擊盜版⚠️)如果你看到這個信息, 說明這是一篇剽竊的文章,請訪問 https://www.cnblogs.com/xgqfrms/ 查看原創文章!
refs
https://www.cnblogs.com/xgqfrms/p/16557404.html
https://www.cnblogs.com/xgqfrms/p/16389706.html
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 發佈文章使用:只允許註冊用戶纔可以訪問!
原創文章,版權所有©️xgqfrms, 禁止轉載 🈲️,侵權必究⚠️!