challenge n人中m人が当選するくじ

n人の中から公平にm人を選ぶ、くじ引きプログラムを作ってください。

Posted feedbacks - JavaScript

こんな感じで使ってください。 alert(['Aさん', 'Bさん', 'Cさん'].lot(2));
1
2
3
4
5
6
Array.prototype.lot = function(n) {
  for(var i=0,r=[];i<n;i++)
    with(Math) with(this)
      r.push(splice(floor(random()*length), 1)[0]);
    return r;
};

元の配列には影響を与えない
alert(["ほ","げ","foo","bar"].cnr(2));
1
2
3
4
Array.prototype.cnr = function(n)
{
	return this.sort(function(){return Math.random()-0.5}).slice(0,n-this.length);
}

Index

Feed

Other

Link

Pathtraq

loading...