跳到主要內容

求出n取k組合的列表 TypeScript 版

有人提到求出n取k組合系列中,JavaScript版本寫得太差,一堆內建轉型別的語法。於是用最近學的TypeScript改寫,應該能夠更容易理解。

class Combinations {
    all: number;
    want: number;
    list: Array<string> = [];

    constructor(total: number, want: number) {
        this.all = total;
        this.want = want;
        this.calc('', total, want);
    }

    addlist(list: Array<string>, head: string, tail: string): void {
        head = head.concat(tail)
        list.push(head);
    };

    calc(before: string, all: number, want: number): void {
        let tail: string = '';
        if (want === 0) {
            tail = "";
            for (let i: number = 0; i < all; i++) {
                tail = tail.concat('0');
            }
            this.addlist(this.list, before, tail);
        } else if (all === want) {
            tail = '';
            for (let j: number = 0; j < all; j++) {
                tail = tail.concat('1');
            }
            this.addlist(this.list, before, tail);
        } else if (all === 1) {
            this.addlist(this.list, before, want.toString());
        } else {  // all must > want
            this.calc(before.concat('0'), all - 1, want);
            this.calc(before.concat('1'), all - 1, want - 1);
        }
    };
}

//主程式
const comb: Combinations = new Combinations(5, 3);

console.log('共:', comb.list.length, '個');
for (let i in comb.list) {
    console.log(comb.list[i]);
}



  

留言

這個網誌中的熱門文章

DBeaver 介面語言

DBeaver是我個人頗常用的一套跨平台Database管理工具,最近升級後發現Windows版本居然變成簡體中文,而且無法切換為英文。

自然人憑證讀卡機驅動程式

鳥毅用的是第一代的自然人憑證讀卡機,EZ100PU(後來有同事買EZmini可以讀SIM卡似乎更好),每年報稅時用一次。 本來只是要申請些政府業務,一時之間找不到光碟,沒想到在 驅動程式下載 居然看到Linux和Mac的驅動程式,剩下的就是政府單位的網頁和程式應該改版了吧!!!

如何將較高版本SQL Server複製到低版本SQL Server (降級為舊版)並保留權限及資料庫圖表

一般若是要將SQL Server裡的Database轉往其他Server時,最簡單的方式就是備份(Backup)後再還原(Restore),或者是䣃離(detach)後附加(attach)。 但是很不幸地,若是由較低版本(e.g. 2008)到較高版本(e.g. 2012)要怎麼辦呢?