星期四, 4月 19, 2012

求出n取k組合的列表 JavaScript 版,同場加映 CoffeeScript版

廢話就不說了,現在的JavaScript比起十幾年前真是好寫多了,語法這幾年來也沒有大改版,所以我這兩年花點時間學了一下現代的JavaScript語法,但程度仍然低落。

我用 node.js 直接在console執行,若沒有可以用瀏覽器的開發者工具試
addlist = function(head, tail) {
  return list.push(head + tail);
};

calc = function(before, all, want) {
  if (want === 0) {
    tail = [];
    for (i=0;i<all;i++) {
      tail += [0];
    }
    addlist(before, tail);
  } else if (all === want) {
      tail = [];
      for (i=0;i<all;i++) {
        tail += [1];
      }
      addlist(before, tail);
  } else if (all === 1) {
    addlist(before, [want]);
  } else {
    calc(before + [0], all - 1, want);
    calc(before + [1], all - 1, want - 1);
  }
};


//主程式
var all = 5;
var want = 3;
var list = [];
calc([], all, want);
console.log('共:', list.length, '個');
for (var i in list) {
  console.log(list[i]);
}

同場加映 CoffeeScript版,純粹練功一下。
addlist=(head, tail)->
   list.push head+tail
calc=(before, all, want) ->
   if want == 0
     tail=[]
     for i in [1..all]
        tail+=[0]
     addlist(before, tail)
   else if all == want
      tail = []
      for i in [1..all]
         tail +=[1]
      addlist(before, tail)
   else if all == 1
      addlist(before, [want])
   else
      calc(before+[0], all-1, want)
      calc(before+[1], all-1, want-1)
#主程式
all=5
want=3
list=[]
calc([], all, want)
console.log '共:', list.length, '個'
for a in list
   console.log a

沒有留言: