-
-
Save xpsteven/122c1b2639772e301f457f5a23df5d07 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { strict as assert } from 'assert'; | |
/** 要組合的對象 */ | |
export interface Item { | |
/** 種類,不得重複 */ | |
type: string; | |
/** 數量,需為正整數 */ | |
amount: number; | |
} | |
/** | |
* 列出所有組合 | |
* @param items 要撿的東西 | |
* @param pick 要挑幾個 | |
*/ | |
function combination<T extends Item = Item> (items: Array<T>, pick: number): Array<Array<T>> { | |
// ... | |
} | |
let result = combination([ | |
{ type: 'Apple', amount: 2 }, | |
{ type: 'Banana', amount: 3 }, | |
{ type: 'Cat', amount: 2 }, | |
{ type: 'Dog', amount: 4 }, | |
{ type: 'Egg', amount: 1 }, | |
], 12); | |
assert(result.length === 1); | |
result = combination([ | |
{ type: 'Apple', amount: 2 }, | |
{ type: 'Banana', amount: 3 }, | |
{ type: 'Cat', amount: 2 }, | |
{ type: 'Dog', amount: 4 }, | |
{ type: 'Egg', amount: 1 }, | |
], 7); | |
result.forEach(ans => { | |
const sum = ans.reduce((prev, curr) => { | |
return prev + curr.amount; | |
}, 0); | |
assert(sum === 7); | |
}); | |
result = combination([ | |
{ type: 'Apple', amount: 2 }, | |
{ type: 'Banana', amount: 3 }, | |
{ type: 'Cat', amount: 2 }, | |
{ type: 'Dog', amount: 4 }, | |
{ type: 'Egg', amount: 1 }, | |
], 13); | |
assert(result.length === 0); | |
result = combination([ | |
{ type: 'Apple', amount: 1 }, | |
{ type: 'Banana', amount: 2 }, | |
{ type: 'Cat', amount: 3 }, | |
], 2); | |
/** A1B1 A1C1 B1C1 B2 C2 */ | |
assert(result.length === 5); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment